What is Middleware in Express.js?
Learn what middleware is in Express.js: how (req, res, next) functions process requests, why order matters, error handling, and practical code examples.
Expected Interview Answer
Middleware in Express.js is a function that has access to the request and response objects and the next function, running in sequence to process a request before it reaches the final route handler.
Each middleware can run code, modify the request or response, end the request-response cycle, or call next() to pass control to the next middleware in the stack. Middleware is used for cross-cutting concerns like body parsing, authentication, logging, and error handling. Order matters: Express executes middleware top to bottom in the order it is registered, and error-handling middleware is identified by its four arguments (err, req, res, next).
- Centralizes cross-cutting logic like auth and logging
- Keeps route handlers focused and clean
- Composable and reusable pipeline stages
- Enables consistent error handling
- Fine-grained control via app-level or route-level scoping
AI Mentor Explanation
Middleware is like the layered checks a delivery passes before a run counts: the umpire checks for a no-ball, then a wide, then the third umpire reviews an appeal. Each official either stops play with a decision or signals to pass it on to the next. Express middleware works the same way — each function inspects the request and either responds or calls next() to hand it down the chain.
Step-by-Step Explanation
Step 1
Write a middleware function
Define a function with (req, res, next) that runs logic on the request.
Step 2
Register it
Use app.use() for app-wide middleware or attach it to a specific route.
Step 3
Call next()
Invoke next() to pass control forward, or send a response to end the cycle.
Step 4
Mind the order
Place middleware before the routes it should affect since execution is top-to-bottom.
Step 5
Add error handling
Define a four-argument (err, req, res, next) middleware last to catch errors.
What Interviewer Expects
- Defines middleware as (req, res, next) functions
- Understands the next() control flow
- Knows middleware order matters
- Can name uses: parsing, auth, logging, error handling
- Recognizes error middleware by its four parameters
Common Mistakes
- Forgetting to call next() so the request hangs
- Placing middleware after the route it should protect
- Sending a response and then calling next()
- Not giving error middleware all four arguments
- Confusing app-level and route-level middleware scope
Best Answer (HR Friendly)
“Middleware in Express is a set of functions that a web request passes through one after another before getting a final answer. Each function can check, change, or stop the request — commonly used for tasks like logging, security checks, and reading the request body.”
Code Example
const express = require('express');
const app = express();
// Runs on every request
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // pass control to the next handler
});
app.get('/', (req, res) => {
res.send('Home');
});
app.listen(3000);// Four arguments identify an error handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong' });
});Follow-up Questions
- What happens if you forget to call next()?
- How does Express identify error-handling middleware?
- What is the difference between app-level and route-level middleware?
- How does middleware order affect request processing?
- Name some built-in and third-party Express middleware.
MCQ Practice
1. What is the signature of a standard Express middleware function?
Standard middleware receives (req, res, next); calling next() passes control to the following middleware.
2. How does Express recognize error-handling middleware?
Express treats a middleware with four parameters, starting with err, as an error handler.
3. What happens if middleware neither responds nor calls next()?
Without next() or a response, the request-response cycle never completes and the request hangs.
Flash Cards
What is Express middleware? — A function with (req, res, next) that processes a request in the pipeline.
Purpose of next()? — Passes control to the next middleware; omitting it stalls the request.
How to register app-wide middleware? — Use app.use(fn) before your routes.
Identify error middleware? — It has four arguments: (err, req, res, next).
Common middleware uses? — Body parsing, authentication, logging, and error handling.