What is Middleware in Express and How It Works
What Is Middleware?
Middleware is a function that runs:
Between request and response
It can:
Modify request
Check authentication
Validate data
Log information
Stop request
Pass request forward
Middleware Analogy
Think of middleware like security checkpoints.
Request enters ↓ Passes through checkpoints ↓ Reaches final route
Request Lifecycle
Basic Middleware Syntax
function middleware(req, res, next) {
console.log("Middleware running");
next();
}
Understanding Parameters
What Does next() Do?
next() passes control to the next middleware or route handler.
Without next():
Request gets stuck
Example
const express = require("express");
const app = express();
function logger(req, res, next) {
console.log("Request received");
next();
}
app.use(logger);
app.get("/", (req, res) => {
res.send("Home Page");
});
app.listen(3000);
Output
Request received
when route is visited.
Middleware Execution Sequence
Types of Middleware
1. Application-Level Middleware
Attached directly to app.
Example
app.use((req, res, next) => {
console.log("Application middleware");
next();
});
Runs for all routes.
2. Router-Level Middleware
Attached to specific router.
Example
const router = express.Router();
router.use((req, res, next) => {
console.log("Router middleware");
next();
});
Runs only for router routes.
3. Built-In Middleware
Express provides built-in middleware.
Example:
app.use(express.json());
Used for parsing JSON request bodies.
Why Built-In Middleware Is Needed
Without express.json():
req.body will be undefined
Middleware Execution Order
Middleware runs in the order it is defined.
Example
app.use((req, res, next) => {
console.log("First");
next();
});
app.use((req, res, next) => {
console.log("Second");
next();
});
Output
First Second
Why Order Matters
Authentication should usually run before protected routes.
Example
Request ↓ Authentication Middleware ↓ Protected Route
Real-World Example: Logging Middleware
function logger(req, res, next) {
console.log(`${req.method} ${req.url}`);
next();
}
app.use(logger);
Example Output
GET /users POST /login
Real-World Example: Authentication Middleware
function auth(req, res, next) {
const token = req.headers.authorization;
if (!token) {
return res.status(401).send("Unauthorized");
}
next();
}
Protected Route
app.get("/dashboard", auth, (req, res) => {
res.send("Protected Dashboard");
});
Real-World Example: Request Validation
function validateUser(req, res, next) {
if (!req.body.name) {
return res.status(400).send("Name required");
}
next();
}
Using Validation Middleware
app.post("/users", validateUser, (req, res) => {
res.send("User created");
});
Multiple Middleware Example
app.get(
"/profile",
logger,
auth,
(req, res) => {
res.send("Profile Page");
}
);
Middleware Pipeline Visualization
Middleware Can End Request Early
Middleware does not always call next().
Example:
function blockRequest(req, res) {
res.send("Blocked");
}
Request ends immediately.
Common Beginner Mistakes
Forgetting next()
Incorrect:
function test(req, res, next) {
console.log("Hello");
}
Request hangs.
Wrong Middleware Order
Bad order:
Protected Route ↓ Authentication Middleware
Authentication should come first.
Practical Example
const express = require("express");
const app = express();
app.use(express.json());
function logger(req, res, next) {
console.log(req.method, req.url);
next();
}
app.use(logger);
app.get("/", (req, res) => {
res.send("Home");
});
app.listen(3000);
Key Takeaways
Final Notes
Middleware is one of the most important Express concepts because it powers:
Authentication
Logging
Validation
Error handling
Security
Request processing
Almost every real-world Express application depends heavily on middleware architecture.
0 Comments
Sign in to join the conversation
No comments yet. Be the first to comment!