Middleware

Small functions that run before a request reaches its route handler. Each one can inspect, change or stop the request.

What is it?

Some work must happen on every (or almost every) request, whatever the route: logging it, checking the user is logged in, parsing the raw body. Repeating that in every handler is tedious and error-prone.

Middleware are functions that sit between the incoming request and its route handler. Each one can look at the request, do some work, and then either pass control to the next function or stop the chain (for example, rejecting an unauthenticated request before it reaches the route).

Explain like I'm 10

Think of airport security between the entrance and your gate: one checkpoint checks your ticket, another scans your bag, another checks your ID. Each one waves you on or stops you if something's wrong. Your route handler is the gate; middleware is everything you pass through to get there.

Examples

A simple logging middleware

function logger(req, res, next) {
  console.log(`${req.method} ${req.url}`);
  next(); // pass control to the next function in line
}

app.use(logger);

app.get("/users", (req, res) => {
  res.json(allUsers);
});

logger runs before every route in this app, because it's registered with app.use() instead of tied to one path.

Middleware that can stop the chain

function requireAuth(req, res, next) {
  if (!req.headers.authorization) {
    return res.status(401).json({ error: "Not authenticated" });
  }
  next();
}

app.get("/orders", requireAuth, (req, res) => {
  res.json(getOrdersFor(req.user));
});

requireAuth is attached to this one route only. If the check fails, it sends a response and never calls next(), so the route handler never runs.

How it works

Middleware runs in the order it's registered, forming a chain. Each function receives (req, res, next): the same request and response as a route handler, plus a next function.

Calling next() moves on to the next middleware, or to the matching route handler at the end of the chain. Not calling next() (for example, because you called res.send()) stops the chain, so nothing after it runs for that request.

Request
   │
   ▼
[logger]  → calls next()
   │
   ▼
[requireAuth]  → calls next() OR sends 401 and stops
   │
   ▼
[route handler]  → sends the final response

Why does it exist?

Middleware lets you write cross-cutting behavior once (logging, auth checks, body parsing, response compression) and apply it to many routes, instead of copy-pasting it into every handler.

When to use it

Use middleware for anything that should happen the same way across many routes: auth checks, request logging, parsing JSON bodies, or rejecting malformed requests before they reach your business logic.

When not to use it

Logic specific to one route, and unlikely to be reused, is usually simpler to write inside that route's handler.

Common mistakes

  • Forgetting to call next(), which leaves the request hanging with no response.

  • Calling next() after sending a response, which causes confusing "headers already sent" errors.

  • Registering middleware in the wrong order, such as putting a route before the auth middleware meant to protect it.

Practice exercises

  1. Easy:

    Write a middleware function that logs the current timestamp for every request.

  2. Medium:

    Write a middleware function that rejects any request missing an x-api-key header with a 401 response.

  3. Hard:

    Explain what happens if a middleware function neither calls next() nor sends a response, and why that's a bug.

Interview questions

What is middleware in a web framework?

A function that runs between an incoming request and its route handler. It can inspect, change, or stop the request before it continues down the chain.

What does calling `next()` do?

It passes control to the next middleware in the chain, or to the matching route handler if none are left.

Give an example of something commonly implemented as middleware.

Authentication checks, request logging, and parsing the request body.

What three parameters does an Express middleware function typically receive, and what is each one for?

req (the incoming request, to read), res (the outgoing response, to write or send), and next (a function that hands control to whatever comes next in the chain).

What happens to a request if a middleware function never calls `next()` and never sends a response?

It hangs. Nothing later in the chain runs, and with no response sent, the client waits until it times out.

Why does forgetting to call `next()` "hang" the request instead of causing an immediate visible error?

Express only knows a middleware is done when it calls next() or sends a response. If neither happens, Express keeps waiting, since doing nothing looks the same as slow work.

Given `app.use(logger)` registered before `app.get("/users", handler)`, in what order do `logger` and `handler` run for a request to `/users`, and why?

logger runs first, then handler. Middleware registered with app.use() runs before the matched route, and logger must call next() for handler to run at all.

What's the difference between middleware registered with `app.use(middleware)` and middleware attached to just one route, like `app.get("/orders", requireAuth, handler)`?

app.use(middleware) runs for every request that reaches it, whatever the path. Middleware passed as an extra argument to a route only runs for that route.

In `requireAuth`, if `req.headers.authorization` is missing, the function calls `res.status(401).json(...)` without calling `next()`. Does the route handler run?

No. next() is never called, so the chain stops at requireAuth and only the 401 response is sent.

Why is `return res.status(401).json(...)` written with a `return` in front of it, rather than calling it on its own line?

The return stops the function there. Without it, execution could reach a later next() call, so the request would both get a response and continue down the chain, causing errors.

What would you expect if a middleware function called both `next()` and `res.send()` for the same request?

The first response really sends. Then, because next() let the chain continue, a later attempt to respond throws a "headers already sent" error, since a request can only be answered once.

Why does the order in which middleware is registered matter, using an auth-check-before-route example?

Middleware runs in registration order, so an auth check must be registered before the route it protects. If it came after, the route handler would already have run and responded.

A developer registers `app.get("/admin", handler)` before the `requireAuth` middleware meant to protect it. What's the consequence?

requireAuth never runs for /admin, because the route already matched, ran and responded. The protection is bypassed completely.

Why is repeating an authentication check inside every route handler worse practice than extracting it into one middleware function?

Every route must remember to include the check correctly, and one missed or wrong copy is a security hole. One shared middleware keeps the logic in one place, fixed once and applied consistently.

What is the airport security analogy illustrating about how middleware functions relate to each other and the final route handler?

Each checkpoint (middleware) either waves you on or stops you, and you only reach the gate (route handler) after passing every checkpoint in order. Middleware is an ordered chain where each link can pass control on or end things early.

If `app.use(logger)` is registered with no path argument, which requests does it run for?

All of them. app.use() without a path applies to every request that reaches that point in the chain, whatever route it matches.

Can a middleware function modify the `req` object before passing it on? Give an example of why that's useful.

Yes. Middleware can attach properties to req for later code. For example, requireAuth can set req.user after checking credentials, so the handler can use req.user without re-checking.

With middleware order `[express.json(), logger, requireAuth, routeHandler]`, why must `express.json()` run before anything that reads `req.body`?

req.body doesn't exist until something reads and parses the raw body. express.json() does that, so anything using req.body, including requireAuth or the handler, must run after it.

What's the difference between middleware meant to run on every request versus middleware scoped to one route or group of routes?

Global middleware (top-level app.use()) runs for all requests. Scoped middleware is passed to specific routes (or app.use() on a path or router) and only runs for requests going there.

Why choose to write logic as middleware rather than calling a regular helper function at the top of each route handler?

Middleware is registered once and applies automatically to every route it's attached to. A helper only works if every developer remembers to call it in every relevant handler.

What does it mean for middleware to "short-circuit" the request? Give an example.

The middleware ends the request itself instead of passing it on. For example, requireAuth sends a 401 and doesn't call next(), so the route handler and any later middleware never run.

Is the route handler itself technically also a kind of middleware in Express?

Effectively, yes. It has the same (req, res, next) shape and sits at the end of the same chain. It's usually called last and ends the chain by sending a response instead of calling next().

If two middleware functions are both registered with `app.use()` and the first calls `next()`, does the second get its own fresh chance to act, or does it just see the first one's finished response?

It gets its own chance to act on the same req and res. Calling next() doesn't finalize anything; it just hands control on, so the second middleware can still inspect or change things before a response is sent.

Why write a validation check like "reject requests missing a required header" as middleware instead of repeating it at the start of every relevant route handler?

As middleware, the check is written once and attached to as many routes as needed (or globally). A new route only needs the existing middleware attached, not a rewritten check.

What real problem would occur if `requireAuth` accidentally called `next()` even when authentication failed?

The chain would continue to the route handler despite missing or invalid credentials, bypassing the auth check and exposing protected routes.

Does calling `next()` inside a middleware function execute the next function immediately and synchronously, and why does this matter?

Yes. next() is an ordinary function call, so the next middleware starts running right away. If that function does async work (like a database call), its code after that point runs later, when the work finishes. This matters when reasoning about order in chains that mix sync and async middleware.

How would you write a middleware function that only logs requests to paths starting with `/api`, while still being registered globally with `app.use()`?

Inside the middleware, check req.path.startsWith("/api") (or similar) before logging, and always call next() whatever the result. One global function can then act on only some requests.

Why is `app.use(express.json())` still considered middleware even though it doesn't reject or check anything?

Middleware doesn't have to check or reject anything. What defines it is sitting in the request chain and calling next(). express.json() transforms the request (parsing the body into req.body) instead of checking it, but it has the same shape and role.