Understanding Middleware
Express middleware functions receive req, res, and next. Middleware can inspect or modify requests, perform authentication, log requests, validate input, and terminate responses.
Middleware executes in registration order. Calling next() passes control to the next matching middleware or route handler.
Express Middleware Chain
Request Logging Middleware
function logger(req, res, next) {
const start = Date.now();
res.on('finish', () => {
console.log(req.method, req.originalUrl, Date.now() - start, 'ms');
});
next();
}
app.use(logger);💡 The middleware records the request start time and logs the response duration when the response finishes.
Key Takeaways
- Middleware runs in registration order.
- Call
next()when middleware does not end the response. - Middleware is useful for cross-cutting concerns.
Knowledge Check
What happens when middleware calls `next()`?