Middleware
Code every matching request passes through on its way to a handler, useful for shared work like auth, logging, and parsing.
See it
What it is
Middleware is code placed in the request path before or after the final handler. It can authenticate a caller, parse JSON, attach a trace ID, log timing, change a response, or stop the request early. Express makes the chain visible with `app.use()` and `next()`; Ruby's Rack and Python's WSGI describe the same stack of wrappers around a handler.
Reach for it when the same transport-level concern belongs on many routes. Keep business rules in handlers or services; middleware is best for work tied to the HTTP boundary. Small, ordered pieces are easier to reason about than one global function doing everything.
Order is behavior. An authorization check registered after a route cannot protect that route, and an error handler in the wrong place may never see the error. Middleware must either send a response or hand off exactly once. Forgetting both leaves the request hanging; doing both causes double-send errors.
Ask AI for it
Add Express 5 middleware in this order: generate or preserve an X-Request-ID, parse JSON with a 1 MB limit, authenticate a Bearer token, and log method, req.originalUrl, status, and duration. Skip auth only for GET /health, attach the verified user to the request, and call next() exactly once; rely on Express 5 forwarding rejected async handlers to the error handler. Finish with a four-argument error handler that returns a stable JSON error code and never leaks stack traces in production.