What is Middleware in Express and How It Works
Introduction
When building backend applications using Express.js, one of the most important concepts you’ll encounter is middleware. Middleware is what gives Express its flexibility and power.
At a high level, middleware acts like a checkpoint system between a client request and the server response.
What is Middleware in Express?
Middleware is simply a function that has access to:
req(request object)res(response object)next(function to pass control)
Basic Syntax
function middleware(req, res, next) {
console.log("Middleware executed");
next();
}
👉 Middleware can:
Modify request/response
End the request-response cycle
Call the next middleware
Where Middleware Sits in the Request Lifecycle
Think of Express as a pipeline:
Client Request → Middleware → Middleware → Route Handler → Response
Each middleware processes the request step by step before reaching the final route handler.
Example Flow
app.use((req, res, next) => {
console.log("Step 1");
next();
});
app.use((req, res, next) => {
console.log("Step 2");
next();
});
app.get("/", (req, res) => {
res.send("Final Response");
});
Execution Order
Step 1 → Step 2 → Route Handler → Response
Types of Middleware in Express
1. Application-Level Middleware
These are bound to the entire app using app.use().
app.use((req, res, next) => {
console.log("App-level middleware");
next();
});
✔ Runs on every request (unless restricted by path)
2. Router-Level Middleware
Used with Express routers (express.Router()).
const router = express.Router();
router.use((req, res, next) => {
console.log("Router middleware");
next();
});
app.use("/api", router);
✔ Only runs for specific route groups (/api here)
3. Built-in Middleware
Express provides some ready-made middleware:
express.json()→ Parses JSON bodyexpress.urlencoded()→ Parses form dataexpress.static()→ Serves static files
app.use(express.json());
✔ Saves time—no need to write common logic manually
Execution Order of Middleware
Middleware executes 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
⚠️ Important: If next() is not called, the request will hang.
Role of next() Function
next() is what moves the request forward in the pipeline.
Without next()
app.use((req, res, next) => {
console.log("Stops here");
});
❌ Request never reaches route handler → client hangs
With next()
app.use((req, res, next) => {
console.log("Continue");
next();
});
✔ Execution continues
Ending Response in Middleware
app.use((req, res, next) => {
res.send("Response from middleware");
});
✔ No need to call next() because response is already sent
Real-World Examples of Middleware
1. Logging Middleware
app.use((req, res, next) => {
console.log(`\({req.method} \){req.url}`);
next();
});
✔ Helps track incoming requests
2. Authentication Middleware
function auth(req, res, next) {
const isLoggedIn = true;
if (!isLoggedIn) {
return res.status(401).send("Unauthorized");
}
next();
}
app.get("/dashboard", auth, (req, res) => {
res.send("Welcome to dashboard");
});
✔ Protects routes
3. Request Validation Middleware
function validate(req, res, next) {
if (!req.body.name) {
return res.status(400).send("Name is required");
}
next();
}
app.post("/user", validate, (req, res) => {
res.send("User created");
});
✔ Ensures clean and valid input
Key Takeaways
Middleware = functions between request and response
They run sequentially
next()controls flowYou can stack multiple middleware
Used for logging, auth, validation, parsing, etc.
Final Analogy
Think of middleware like security checkpoints at an airport:
Passport check → Security scan → Boarding gate
Each step verifies something before allowing you forward
Similarly:
Request → Middleware checks → Final Response
Conclusion
Middleware is the backbone of Express applications. Once you understand how middleware flows and how next() works, you gain fine-grained control over request handling.
Mastering middleware is essential for building scalable, maintainable backend systems.