Interview Q&A / Node.js

BeginnerQuick answer1 min readUpdated 3 Oct 2026

Why does the order of middleware and routes matter in Express?

SHORT ANSWER

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

js
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 last

Typical safe order:

  1. Security headers, CORS, logging.
  2. Body parsers.
  3. Authentication.
  4. Routes.
  5. 404 handler.
  6. 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.

#express#middleware#routing

Related questions

Practise more Node.js questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Node.js quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.