Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 43 ยท Middleware

How Middleware Works

Understand Express middleware: the (req, res, next) signature, why order matters, path-scoped app.use, short-circuiting and how errors skip the normal chain.

Almost everything interesting in Express is middleware. Logging, reading JSON bodies, checking a login, compressing responses, even your route handlers: they are all functions that receive a request, may do something with it, and either answer or pass it on. Once you understand this one idea, the rest of the framework fits together.

A middleware function is any function with the signature (req, res, next). It can read or change req and res, send a response itself, or call next() to hand the request to the next function in line.

The shape of a middleware

Here is a minimal logger in real Express code (read-only on this site):

JavaScript
import express from 'express';

const app = express();

app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

app.get('/', (req, res) => {
  res.send('Hello');
});

app.use(fn) registers a function that runs for every request, whatever its method or path. The logger prints a line and calls next(), so Express carries on to the next matching function, here the / route. A route handler is just middleware that usually does not call next(), because it ends the request by sending a response.

A middleware has three choices

Call next() Pass the request on to the next function.
Respond Send a response and stop the chain.
Pass an error next(err) jumps to the error handlers.

Doing none of these leaves the request hanging.

1 / 2

The chain and its order

Express keeps one ordered list of functions. For each request it starts at the top, runs the first one that matches, and moves down only when that function calls next(). Registration order is execution order.

sequenceDiagram
  participant C as Client
  participant L as logger
  participant A as auth check
  participant H as route handler
  C->>L: GET /secret
  L->>A: next()
  A->>H: next()
  H-->>C: res.json(...)

Each middleware calls next() to pass the request along; the handler finally answers.

The stand-in below is a small mini Express. Skim past its framework block to the lines after stand-in framework: end.

Node.js Middleware runs in the order you register it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the numbered lines come out in 1, 2, 3 order and that the second middleware's change to req is visible to the handler. This is the standard way to share data between steps: attach it to req (or to res.locals in real Express).

Order mistakes

Because order is everything, the same two functions can behave very differently depending on where you place them.

Node.js A middleware registered too late never runs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Only /late is logged. The logger sits below the /early route, and that route answered without calling next(). In a real app, put general middleware (logging, body parsing, security headers) above the routes that need it, and error handlers below everything.

Short-circuiting

A middleware can stop the chain by sending a response and not calling next(). Guards use this all the time:

JavaScript
function requireKey(req, res, next) {
  if (req.get('x-api-key') !== 'secret') {
    return res.status(401).json({ error: 'API key required' });
  }
  next();
}

app.get('/private', requireKey, (req, res) => {
  res.json({ data: 'for key holders only' });
});

Note the return. Without it the function would send the 401 and then continue to next(), and the handler would try to send a second response. Express then throws "Cannot set headers after they are sent". The pattern return res...; or if (...) { res...; return; } is a habit worth building.

Never call next() after you have sent a response, and never leave a path where a middleware neither responds nor calls next(). The client waits until it times out.

Path-scoped middleware

app.use takes an optional path prefix. The function then runs only when the URL starts with that prefix, and req.path inside it is relative to the prefix, exactly as with routers in Modular Routing.

JavaScript
app.use('/admin', requireAdmin);          // /admin, /admin/users, ...
app.use('/api', express.json());          // only API routes parse JSON
app.get('/stats', requireKey, showStats); // only this route

/admin also matches /admin/ and /admin/anything, but not /administrator; the match is on whole path segments.

Node.js Scoped middleware and short-circuiting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The public page never triggers the admin guard. The second call is stopped by the guard (403) and never reaches the route; the third passes the guard and reaches the route.

Errors skip the normal chain

If a middleware calls next(err) (or throws), Express skips every normal function and jumps to the next error-handling middleware, which has four parameters: (err, req, res, next). Express 5 also forwards a rejected promise from an async function for you. The error handling lesson covers this fully; for now just know that error handlers are registered after the routes:

JavaScript
app.use((err, req, res, next) => {
  res.status(500).json({ error: err.message });
});
Node.js next(err) skips normal middleware

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Real Express versus the stand-in

The (req, res, next) signature, ordering rules, short-circuiting, prefix matching and four-argument error handlers above are the real behavior. The stand-in differs in small ways: real Express also lets next('route') skip the rest of the current route's handlers and next('router') leave the current router, offers res.locals for per-request data, and supports app.use with arrays, regular expressions and several handlers at once. The stand-in supports the common cases only.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What makes a function a middleware in Express?

    Express passes req, res and next to each function in the chain. That signature is what makes it middleware.
  2. 2. A middleware logs the request but forgets to call next() or send a response. What does the client experience?

    Nothing finishes the response and nothing continues the chain, so the connection stays open.
  3. 3. You register app.get('/a', handler) and then app.use(logger). The handler sends a response. Does the logger run for GET /a?

    Order is execution order. The route answered and ended the chain before reaching the logger.
  4. 4. What does app.use('/admin', guard) match?

    A use path is a prefix, so /admin and everything below it match, though /administrator does not.
  5. 5. What happens when a middleware calls next(new Error('x'))?

    Passing an argument to next signals an error, and only functions with four parameters handle it.

Summary

  • Middleware is any function (req, res, next); route handlers are middleware too.
  • Express runs the matching functions in registration order.
  • A middleware either responds, calls next(), or passes an error with next(err).
  • Put general middleware above the routes it should affect and error handlers at the bottom.
  • app.use(prefix, fn) limits a function to a path prefix; add middleware to a single route by listing it before the handler.
  • Return after responding, so next() is never called as well.

Next: Built-in Middleware.