DEV Community

Cover image for Step Up Your Express.js Game: Advanced Middleware and Security Tips for Beginners
Ashok Naik
Ashok Naik

Posted on

3

Step Up Your Express.js Game: Advanced Middleware and Security Tips for Beginners

Express.js is a popular framework for developing web apps in Node.js. Middleware is a fundamental aspect that contributes to Express's power and flexibility. If you're familiar with the fundamentals of Express middleware, you'll recognize that it's similar to a set of steps your request takes. But what happens after the basics? Let's get started and examine sophisticated middleware topics in a basic manner.

Middleware be like: "I'm just a simple middleware, but when things get tough, I call my next()"

What is Middleware?

Middleware functions have access to the request object (req), the response object (res), and the following middleware function in the application's request-response cycle. These functions can execute a variety of activities, including altering the request or response objects, terminating the request-response cycle, and calling the next middleware in the stack.

Real-World Example: A Bakery
Imagine you own a bakery, and your shop is the server. Customers (requests) come in, and they have to go through several stages (middleware) to get their bread (response).

  1. Request logging: A staff member logs the customer’s details.
  2. Authorization: Another staff member checks if the customer has a valid membership card.
  3. Processing order: The baker prepares the bread.
  4. Packaging: Another staff member packs the bread.
  5. Sending response: Finally, the cashier hands over the packed bread to the customer.

1. Error Handling Middleware:

Sometimes things go wrong, and you need a way to catch and handle errors. Error-handling middleware functions have four arguments: err, req, res, and next.

app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});

Enter fullscreen mode Exit fullscreen mode

2.Chaining Middleware:

You can create modular middleware functions and chain them together for reusability and cleaner code.

const checkAuth = (req, res, next) => {
    if (req.user) {
        next();
    } else {
        res.status(401).send('Unauthorized');
    }
};

const logRequest = (req, res, next) => {
    console.log(`${req.method} ${req.url}`);
    next();
};

app.use(logRequest);
app.use(checkAuth);

Enter fullscreen mode Exit fullscreen mode

3.Custom Middleware for Specific Tasks

Sometimes you need middleware to perform specific tasks like data validation, rate limiting, or even modifying the request object to include additional information.

const addTimestamp = (req, res, next) => {
    req.requestTime = Date.now();
    next();
};

app.use(addTimestamp);

Enter fullscreen mode Exit fullscreen mode

Security Best Practices

1.Helmet Middleware:

When designing applications with Express.js, security is critical. Below are some lesser-known security guidelines and recommended practices that can help protect your application:

Helmet Middleware secures Express apps by setting multiple HTTP headers. It consists of a group of smaller middleware methods that set security-related HTTP headers.

const helmet = require('helmet');
app.use(helmet());

Enter fullscreen mode Exit fullscreen mode

2.Rate Limiting:

Rate restriction prevents brute-force assaults by restricting the amount of requests a user can make in a given time period.

const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15 minutes
    max: 100, // limit each IP to 100 requests per windowMs
});

app.use(limiter);

Enter fullscreen mode Exit fullscreen mode

3.Content Security Policy (CSP):

CSP helps prevent cross-site scripting (XSS) attacks by specifying which content sources are trusted.

app.use(helmet.contentSecurityPolicy({
    directives: {
        defaultSrc: ["'self'"],
        scriptSrc: ["'self'", "trusted.com"]
    }
}));
Enter fullscreen mode Exit fullscreen mode

Just like you would take every precaution to keep your bakery safe and running properly, these techniques will help keep your web application secure and dependable.

Thank you for the Read!

Billboard image

Monitoring as code

With Checkly, you can use Playwright tests and Javascript to monitor end-to-end scenarios in your NextJS, Astro, Remix, or other application.

Get started now!

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay