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 flavours(๐Ÿ˜›), each serving a unique purpose

flavour

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 (14)

Collapse
 
aaditya_vikram profile image
Aaditya Vikram

Absolutely loved this post! ๐Ÿ™Œ

The way you compared the different types of middleware in Express.js to flavors and ingredients really made the concept come alive! ๐Ÿด The analogy of middleware as layers in a sandwich or secret sauces in cooking is a perfect way to explain how middleware works in Expressโ€”especially for those who might be newer to the framework.

I particularly liked how you broke down the different types like application-level, router-level, and error-handling middleware with relatable examples. It makes understanding and implementing them so much easier! The section on composing middleware really highlights how powerful Express.js can be when it comes to creating flexible and reusable code. It feels like you've truly mastered the art of making middleware fun and approachable. ๐Ÿ‘ฉ๐Ÿปโ€๐Ÿณ

Looking forward to more of your insightful and engaging posts! Keep up the amazing work! ๐Ÿš€

Collapse
 
khushindpatel profile image
Khushi Patel

Sure @aaditya_vikram Stay connected ! ๐Ÿ™Œ๐Ÿป

Collapse
 
margish288 profile image
Margish Patel • Edited

Such a informative blog๐Ÿ”ฅ

Collapse
 
muhammad_shamsparacha_94 profile image
Muhammad Shams Paracha

Khushi Patel ! This was really a difficult part for me. But your valuable sauce solved my problem ๐Ÿ˜Š

Collapse
 
khushindpatel profile image
Khushi Patel

I am glad to here that this helps you

Collapse
 
muhammad_shamsparacha_94 profile image
Muhammad Shams Paracha

I am actually beginner in MERN stack and i just learn new concepts. if i need your help please guide me... thanks

Collapse
 
khushindpatel profile image
Khushi Patel

I am coder by passion and creative by heart ! ๐Ÿ’“๐Ÿซฃ

Collapse
 
prashantnirgun profile image
Prashant Nirgun

เคฎเฅˆเคกเคฎ เคœเคพเคจ เคฌเฅเค เค•เคฐ เค†เคช เค•เฅ‹ เคธเคฎเคเฅ‡ เค”เคฐ เคตเคฟเคฆเฅ‡เคถเฅ€ เคจเคพ เคธเคฎเคเฅ‡ เค‡เคธ เคฒเคฟเค เคนเคฟเค‚เคฆเฅ€ เคฎเฅ‡เค‚ เคฒเคฟเค– เคฐเคนเฅ‡ เคนเฅˆเฅค เคฏเฅ‡ เคธเฅˆเค‚เคกเฅ€เคตเคฟเคš เค•เฅ€ เคฐเฅ‡เคธเคฟเคชเฅ€ เค•เฅ‹ เคฒเฅ‡เค•เคฐ เคœเฅ‹ เคœเฅเคžเคพเคจ เคชเฅ‡เคฒ เคฐเคนเฅ€ เคนเฅ‹ เคฏเฅ‡ เคคเฅ‹ เคนเคฐ เคœเค—เคน เคชเคฐเฅเคฏเคพเคชเฅเคค เคฎเคพเคคเฅเคฐเคพ เคฎเฅ‡เค‚ เค‰เคชเคฒเคฌเฅเคง เคนเฅˆ เฅค เคฆเฅ‹ เคชเฅ‹เคธเฅเคŸ เคชเคขเคผเคจเฅ‡ เค•เฅ‡ เคฌเคพเคฆ เคกเฅ‡เคตเคฒเคชเคฐ เค•เฅ‡ เคนเคพเคฅ เคฎเฅ‡เค‚ เค•เฅเคฏเคพ เคนเฅˆ เฅค

Collapse
 
codejourney profile image
Info Comment hidden by post author - thread only accessible via permalink
Ashish Vaghela

Great efforts ๐Ÿ™Œ
During formatting (conclusion part) AI did some mistake (markup related)

Collapse
 
khushindpatel profile image
Khushi Patel

Which mistake?

Collapse
 
aaditya_vikram profile image
Info Comment hidden by post author - thread only accessible via permalink

Conclusion: Middleware Mastery ๐Ÿ‘ฉ๐Ÿปโ€๐Ÿณ *
He is saying that remove these asterisk sign (
) from Conclusion heading.
That's all.

 
codejourney profile image
Info Comment hidden by post author - thread only accessible via permalink
Ashish Vaghela

hahaha
because most of these GPT or LLM's gives output in markdown format

Collapse
 
codejourney profile image
Ashish Vaghela

*Conclusion: Middleware Mastery ๐Ÿ‘ฉ๐Ÿปโ€๐Ÿณ *

AI (Probably ChatGPT gives output in markdown format
so this title was supposed to be in bold format.

however you're helping many devs by sharing such valuable information
keep in up.

Collapse
 
hanzla-mirza profile image
Mirza Hanzla

๐Ÿ‘๐Ÿ‘๐Ÿ‘๐Ÿ‘

Some comments have been hidden by the post's author - find out more