Routing

A route is three things bound together: an HTTP method, a path pattern, and one or more handler functions. app.get('/books/:id', handler) says when a GET request arrives whose path matches /books/:id, run handler. Everything else in Express 24,430 — middleware, error handling, routers — is built on that one idea, so getting routing right is most of getting Express right.

The router keeps one ordered list of layers, and each app.get, app.post or app.use call appends to it. When a request arrives, Express walks the list from the top asking two questions of each layer: does the path match, and does the method match? The first layer answering yes to both gets the request. If its handler calls next(), the walk resumes below it; if nothing ever responds, Express falls off the end and its built-in final handler sends a 404.

That "first match wins, in registration order" rule is the single most useful thing to remember. It explains why /books/featured must be registered before /books/:id, why a catch-all 404 belongs at the bottom of the file, and why app.use(express.json()) placed after your routes silently does nothing.

Express 5 also changed how path patterns are written, upgrading to path-to-regexp 8 and dropping the regular-expression-flavored syntax Express 4 accepted. Patterns such as /files/* and /books/:id? now throw at startup instead of matching, so the new syntax is the difference between a server that boots and one that does not.

How Express dispatches one request through its ordered layer stack
How Express dispatches one request through its ordered layer stack

Subsections