mediumConceptDesignMidSenior
Walk me through the middleware chain of an Express service. What has to come before what, and why?
4 min readUpdated 2026-08-15
Answer
Short answer
Middleware runs in registration order, so ordering is behaviour rather than style: the request id precedes logging, the body parser precedes anything reading the body, authentication precedes authorisation, and the error handler goes last because Express only searches forward from the failure.
Was this answer helpful?
Likely follow-ups
- You register the error handler before your routes. What happens?
- An async route handler throws. Does your error middleware see it?
- Why should the body parser have a size limit, and what happens without one?
- Where does a response-time header have to be set, given that headers flush with the first write?
Related questions
- Your logs are full of Cannot set headers after they are sent. Walk me through how a request gets into that state.mediumAlso on express and error-handling4 min
- A request fails but your Express error-handling middleware never runs. How do you work out why?mediumAlso on express and error-handling4 min
- How do you design the error contract for an API that other teams have to program against?hardAlso on error-handling6 min
- You stream the model's answer token by token to the browser. What does that change about error handling, guardrails and cost?hardAlso on error-handling5 min