Express route order and matching
top-down route matching.
Express checks routes in definition order, /items/new matches the literal route first, if /:id came first new would be captured as an id.
thinking Express picks the most specific route automatically.
WHAT THIS TESTS This examines whether you understand Express's middleware and routing model: routes are tried in the order they are registered, first match wins, with no notion of specificity ranking.
A GOOD ANSWER COVERS Express evaluates routes top to bottom in definition order. The first route whose method and path pattern match the request handles it, and unless that handler calls next, the search stops. The literal route /items/new and the parameterized route /items/:id both match the URL /items/new, because :id is a wildcard segment that captures any value, including the string 'new'. In the given order, the literal route is defined first, so /items/new hits it as intended. If the order were reversed and /items/:id came first, that route would match /items/new, set req.params.id to 'new', and the literal handler would never run. This is why you place specific, literal routes before parameterized ones. Express has no automatic specificity resolution; you control precedence purely through ordering.
COMMON WRONG ANSWERS Believing Express prefers the more specific literal route regardless of order. Thinking both handlers run for one request. Forgetting that :id matches any non-slash segment, including words like new.
LIKELY FOLLOW-UPS How does calling next inside a handler change this. How would a regex or constraint on :id avoid the collision. How does this ordering rule apply to middleware generally.
ONE CONCRETE EXAMPLE With /items/:id first, a request to /items/new logs id = 'new' and serves the show page instead of the new-item form, a subtle bug. Reordering so /items/new precedes /items/:id fixes it: /items/new hits the literal route, and /items/123 falls through to the parameterized one.
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.