Introduction: What’s Cooking in Express.js? 👀👩🏻🍳
If you’ve spent any time in the Node.js kitchen⏲️, you’ve probably heard about Express.js, But what’s the secret ingredient that makes Express so powerful? it’s the magic of middleware. Think of middleware as the secret sauce that adds flavour to your application, making everything come together just right.🥢
What Exactly is Middleware?🫸🏻😛🫷🏻
Imagine you’re at a sandwich shop. You place your order, and before your sandwich reaches you, it goes through a series of steps: the bread is toasted, the veggies are added, the sauce is spread, and finally, it’s wrapped up. Middleware in Express.js works the same way. When a request comes in, it passes through a series of functions (aka middleware) before reaching the final destination (your route handler).
In other words, middleware is like the conveyor belt in a sandwich shop, where each function adds its own special touch to the request or response.
The Basic Recipe: How Middleware Works
Here’s a simple recipe to understand middleware:
- Request comes in (bread is placed on the counter).🍞
- Middleware does something to the request or response (veggies and sauce are added).🥙
- Next middleware in the stack (if any) does its job (maybe more toppings?).🧂
- Response is sent back (the sandwich is ready to eat).🥪
Here’s a quick example in code:
const express = require('express');
const app = express();
// Simple middleware that logs every request
app.use((req, res, next) => {
console.log(`${req.method} request for ${req.url}`);
next(); // Move to the next middleware or route handler
});
// Route handler
app.get('/', (req, res) => {
res.send('Hello, Middleware!');
});
app.listen(3000, () => console.log('Server running on port 3000'));
In this recipe, the middleware logs each request before the route handler sends the response.
Okay now , I will see you in next blog for types of middleware!
Happy Coding ! 🫶🏻
Top comments (12)
Thanks!!
Best information
Well, it's just an interceptor...
Love the sandwich analogy! Middleware truly is the unsung hero of Express.js, making everything work smoothly behind the scenes. Can't wait to dive into its different types!
I like it 👍👍👍👍👍👍👍👍👍
That sure is a good reaction count for a couple of days.
The best blog of the day 🙌🙌
Glad you like this! added second part today
please read and review ! 🙌🏻👩🏻🍳
To understand middleware in Node.js, think of it as a checkpoint on a road. Imagine you're driving from point A (client request) to point B (server response). Along the way, you might pass through different checkpoints (middleware) that perform specific actions, such as:
Checking your ID (authentication middleware)
Inspecting your cargo (parsing JSON or form data)
Paying a toll (logging or rate-limiting)
Clearing customs (validating data)
Each checkpoint can either let you continue your journey, modify your path, or stop you entirely.
Title: Mastering Middleware 🗿
Reality: what is middleware🤡
you might had ignore the beginner tag here !