Middleware execution order and sharing data via req
the sequential pipeline and shared req object.
middleware runs top-down in registration order; each calls next(); attach data like req.user that later handlers read.
assuming parallel execution or using globals to pass state.
WHAT THIS TESTS This tests your mental model of the Express request pipeline as a sequential chain and how state travels between stages.
A GOOD ANSWER COVERS Middleware executes synchronously in the order it is registered. With logging registered first, then authentication, then the route, an incoming request hits the logger, which records and calls next(); then authentication runs, validates credentials, and calls next(); finally the route handler runs and sends the response. Crucially, Express creates one req and one res object per request and passes the same references down the chain. So authentication can attach data, for example req.user = decodedUser, and any later middleware or the route handler can read req.user. This is the idiomatic way to pass per-request state, rather than globals which would leak across concurrent requests.
COMMON WRONG ANSWERS Believing the middleware run concurrently or in parallel. Using a module-level variable to store the current user, which is shared across all simultaneous requests and causes data bleed. Assuming order does not matter, then wondering why the handler sees no req.user. Forgetting next() and stalling the chain.
LIKELY FOLLOW-UPS What happens if logging is registered after authentication? How do you short-circuit the chain on auth failure (call res.status(401) and do not call next())? Why are globals dangerous under concurrency?
ONE CONCRETE EXAMPLE app.use(logger); app.use((req, res, next) => { req.user = verify(req.headers.authorization); next(); }); app.get('/me', (req, res) => res.json(req.user)); The logger fires first, then auth attaches req.user, then /me reads it. Because req is per-request, two simultaneous users never see each other's data, which a shared global variable would not guarantee.
Read the original → expressjs.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.