What is Middleware in Express and How It Works

Like to study,fitness freak,my looks is my first priority, hardworking person, like discipline and love to learn new thing
π Introduction
When a request hits your Express server, it doesnβt go directly to the route handler.
π It passes through multiple checkpoints first β these are called middleware
Middleware is one of the most important concepts in Express π₯
π§ What Is Middleware?
Middleware is:
π A function that runs between the request and the response
It can:
Modify request (
req)Modify response (
res)End the request
Pass control to the next function
π§© Simple Analogy: Request Pipeline
Think of middleware like a pipeline π°
Request β Middleware β Middleware β Route Handler β Response
π Each step can inspect or modify the request
π Diagram Idea: Middleware Flow
Client β Request β Middleware β Route β Response
βοΈ Where Middleware Sits
Middleware sits:
π Between incoming request and final response
app.use((req, res, next) => {
console.log("Middleware executed");
next();
});
π Role of next() Function
π next() passes control to the next middleware
app.use((req, res, next) => {
console.log("Step 1");
next();
});
π Without next() β request will hang β
π Diagram Idea: Execution Chain
Middleware1 β Middleware2 β Middleware3 β Route
π§ Types of Middleware
1οΈβ£ Application-Level Middleware
Applied to the whole app:
app.use((req, res, next) => {
console.log("App-level middleware");
next();
});
2οΈβ£ Router-Level Middleware
Applied to specific routes:
app.get("/user", (req, res, next) => {
console.log("Route middleware");
next();
}, (req, res) => {
res.send("User route");
});
3οΈβ£ Built-in Middleware
Provided by Express:
app.use(express.json());
π Parses JSON request body
βοΈ Execution Order of Middleware
π Middleware runs in the order it is defined
app.use((req, res, next) => {
console.log("First");
next();
});
app.use((req, res, next) => {
console.log("Second");
next();
});
π Output:
First
Second
π Real-World Examples
1οΈβ£ Logging Middleware
app.use((req, res, next) => {
console.log(`\({req.method} \){req.url}`);
next();
});
2οΈβ£ Authentication Middleware
function auth(req, res, next) {
if (req.headers.token) {
next();
} else {
res.send("Unauthorized");
}
}
3οΈβ£ Request Validation
function validate(req, res, next) {
if (!req.body.name) {
return res.send("Name required");
}
next();
}
π§ Conceptual Understanding
π Middleware = Gatekeeper πͺ π It checks and processes requests before reaching the final handler
π Conclusion
Middleware is the backbone of Express applications.
It helps you:
Organize logic
Reuse code
Control request flow
β¨ Final Tip
If your logic repeats across routes β make it middleware π
