Express in Depth: Routing and Middleware
How a request really travels through your app - and how to shape that journey
app.get and app.use and things worked. Now we open the hood. An Express app is really a pipeline: every request flows through an ordered list of functions - middleware and route handlers - until one of them sends a response or an error is thrown. Master the order of that pipeline and you control everything: authentication, logging, parsing, routing, and error handling.
- explain the middleware chain and the exact job of
next(), - reason precisely about why order of registration matters,
- split routes into modular files with
express.Router(), - read route parameters, including multiple and optional params,
- write centralized error-handling middleware (the four-argument kind).
1. The request pipeline
Every function you register with app.use, app.get, app.post and friends is pushed onto a single ordered stack. When a request arrives, Express walks that stack from top to bottom, running each function whose path and method match. A function that receives control has exactly three ways to continue:
- Send a response - call
res.send,res.json,res.end, etc. The pipeline stops; nothing below runs. - Call
next()- pass control to the next matching function in the stack. - Call
next(err)- jump straight to the error-handling middleware (more on that in section 5).
A plain middleware function has the signature (req, res, next). A route handler is just a middleware that happens to be bound to a specific method and path. This is the single most important mental model in Express: there is no magic, only an ordered list of functions.
Analogy. Think of an assembly line in a factory. A part (the request) rides the conveyor belt past a series of stations (middleware). Each station can inspect or modify the part and wave it on with next(), or pull it off the line entirely by shipping a finished product (res.send). If a station hits a defect it drops the part into the "reject" chute - that is next(err), and the reject chute leads to one special station: the error handler.