Why does the order of middleware and routes matter in Express?
Express runs middleware and routes in the order they are registered, and a response ends the chain. A parser placed after a route never runs for it, and a catch-all placed early swallows later routes.
Explain it simply
Think of a queue of counters at a passport office: document check, photo, fee payment, final desk. The order is the process. If the fee counter came first, applicants would pay before their documents were verified. Express lines up your app.use and route calls the same way and passes each request along until someone replies.
Example
const express = require("express");
const app = express();
// wrong: this route is hit before the parser is registered
app.post("/login", (req, res) => res.json(req.body)); // req.body is undefined
app.use(express.json()); // too late for the route above
// correct order
app.use(express.json()); // 1. parse body
app.use(logger); // 2. log every request
app.use("/api", authRouter); // 3. specific routes
app.use((req, res) => res.sendStatus(404)); // 4. fallback
app.use(errorHandler); // 5. errors lastTypical safe order:
- Security headers, CORS, logging.
- Body parsers.
- Authentication.
- Routes.
- 404 handler.
- Error handler.
A middleware that forgets to call next() or send a response leaves the request hanging until the client times out.
What to say in the interview
"Express matches in registration order. Parsers and auth must come before routes, the 404 handler after routes, and the error handler last. Each middleware must either respond or call next."
Common mistakes
- Putting
app.use(express.static(...))or a wildcard route above more specific routes. - Calling
next()after already sending a response, causing a "headers already sent" error.