DEV Community

Khushi Patel
Khushi Patel

Posted on

Types of Middleware: The Different Flavors

After reading last post let's see types of middleware in ExpressJs ,Middleware comes in different flavors(😛), each serving a unique purpose:

1. Application-level Middleware: This is like the main ingredient. You add it to your whole application, and it runs on every request.🫡

app.use((req, res, next) => {
    console.log('This runs on every request!');
    next();
});
Enter fullscreen mode Exit fullscreen mode

2. Router-level Middleware: This is more like a specialty topping. It’s used for specific routes or groups of routes.🤓

const router = express.Router();
router.use('/special', (req, res, next) => {
    console.log('Special route middleware!');
    next();
});
Enter fullscreen mode Exit fullscreen mode

3. Built-in Middleware: These are like pre-made sauces that come with Express, such as express.json() for parsing JSON. 😌

app.use(express.json());
Enter fullscreen mode Exit fullscreen mode

4. Error-handling Middleware: This is the chef’s secret weapon. It catches any errors and serves up a custom response. 😎

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

The Power of Composing Middleware 🫱🏻‍🫲🏽

One of the coolest things about middleware is that you can stack them together to create complex workflows. Each middleware function can either end the request-response cycle or pass control to the next function using next(). This makes it easy to add features like authentication, logging, error handling, and more—just like adding layers to your sandwich.
Here’s how you might use middleware to protect a route:

const authenticate = (req, res, next) => {
    if (req.isAuthenticated()) {
        return next();
    }
    res.redirect('/login');
};

app.get('/dashboard', authenticate, (req, res) => {
    res.send('Welcome to your dashboard!');
});

Enter fullscreen mode Exit fullscreen mode

In this example, the authenticate middleware checks if the user is authenticated before allowing them to access the dashboard.

*Conclusion: Middleware Mastery 👩🏻‍🍳 *
Middleware is truly the secret sauce of Express.js, adding layers of functionality to your Node.js applications. Whether you’re handling requests, managing responses, or catching errors, mastering middleware will make your code cleaner, more organised, and a lot more powerful.

So next time you’re building an Express.js app, think about the flavors you can add with middleware. Mix, match, and create your own secret sauce—it’s what makes your application uniquely yours!

Happy C̶o̶o̶k̶i̶n̶g̶ Coding! 🫶🏻

Top comments (1)

Collapse
 
hanzla-mirza profile image
Mirza Hanzla

👍👍👍👍👍👍