Express Middleware and the Request Lifecycle
Express middleware is a chain of functions that each get req, res and next. Every Express interview asks how the chain works, why order matters, and how error-handling middleware differs from normal middleware.
What you will learn
- Explain the middleware chain and next()
- Order middleware correctly (security, parsing, auth, routes, errors)
- Write router-level and route-level middleware
- Know what changed in Express 5
Key concepts
Middleware
A function (req, res, next). It can read or change req and res, end the response, or call next() to pass control on. If it does neither, the request hangs.
Error middleware
A function with four arguments (err, req, res, next). Express jumps to it when any middleware calls next(err) or throws.
Express 5
Rejected promises from async handlers are passed to next(err) automatically, so you no longer need a wrapper. Path syntax also changed (wildcards must be named, e.g. /*splat).
Step by step
A typical order
app.use(helmet()) // security headers
app.use(cors(corsOptions))
app.use(express.json({ limit: '1mb' }))
app.use(requestId) // add req.id for logs
app.use(httpLogger)
app.use('/api', rateLimiter)
app.use('/api', authRouter) // public
app.use('/api', requireAuth, apiRouter)
app.use(notFoundHandler) // 404 for unknown routes
app.use(errorHandler) // always lastExamples
Auth middleware
export function requireAuth(req, res, next) {
const token = req.get('authorization')?.replace(/^Bearer /, '')
if (!token) return res.status(401).json({ error: 'Login required' })
try {
req.user = jwt.verify(token, process.env.JWT_SECRET)
next()
} catch {
res.status(401).json({ error: 'Invalid or expired token' })
}
}
export const requireRole = (role) => (req, res, next) =>
req.user.roles.includes(role) ? next() : res.status(403).json({ error: 'Forbidden' })Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Write a middleware that logs method, path, status and duration for every request.
- Explain what happens if the error handler is registered before the routes.
- Write a timeout middleware that returns 503 after 5 seconds.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
What is the difference between app.use and app.get?
app.use mounts middleware for every method on a path prefix (/api matches /api/users). app.get matches only GET on that exact route pattern.
How do you catch errors from async handlers in Express 4?
Wrap the handler: const wrap = fn => (req, res, next) => fn(req, res, next).catch(next), or use express-async-errors. Express 5 does this natively.
Summary
Middleware runs in order; each one ends the response or calls next. Put security and parsing first, auth before protected routes, a 404 handler after routes, and the four-argument error handler last.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus