How does middleware work in Express, and how would you write your own?
Express middleware is a function with the signature (req, res, next). Express keeps an ordered stack of them and passes the request down that stack; each one can read or modify req and res, then either end the response or call next() to hand control on.
function requestTimer(req, res, next) {
const start = process.hrtime.bigint();
res.on('finish', () => {
const ms = Number(process.hrtime.bigint() - start) / 1e6;
console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${ms.toFixed(1)}ms`);
});
next();
}
app.use(requestTimer);The rules that matter:
- Order is everything.
app.useregisters in sequence, so a body parser must come before the route that readsreq.body, and an auth check must come before the handler it protects. - Forgetting
next()hangs the request — no error, just a client waiting until it times out. - Error middleware takes four arguments,
(err, req, res, next). Express identifies it by arity, and it must be registered last.





