← Back to Node.js, page 4

nodejs-0066 · Easy fresher

What is middleware, and how does a middleware chain with next() work?

Middleware is a function that receives the request, the response and a next function. It can read or change the request, end the response, or call next() to pass control to the following function. The chain runs in the order the functions were added, and code after next() runs again when the later steps are finished.

Full answer

Frameworks such as Express and Koa organise request handling as a list of small functions. Each function has one job: logging, parsing JSON, authentication, rate limiting, routing, or an error response.

Contract of a middleware (req, res, next):

  1. Do some work with req and res.
  2. Either end the response (res.end, res.json) or call next() to continue.
  3. If you do neither, the request hangs.
  4. If something fails, call next(err) (in Express) so that error handling middleware takes over.

Order matters. A body parser must come before the code that reads req.body. An authentication step must come before protected routes. A 404 handler comes after all routes, and error handlers come last.

The "onion" idea: code before next() runs on the way in. After next() returns (or its promise resolves, in Koa style) code runs on the way out. This is how a timing middleware measures the whole request.

Implementing the chain needs only a short function: keep an index, call the function at that index with a next that increments it. Express does exactly this, plus routing by method and path, and error middleware that has four parameters (err, req, res, next).

Using the pattern in your own code (command handlers, message consumers, API clients) is a clean way to add cross-cutting features without touching business code.

javascript
const http = require('node:http');

// A tiny middleware runner, similar in idea to Express.
function createApp() {
  const stack = [];
  const app = (req, res) => {
    let index = 0;
    const next = (err) => {
      const fn = stack[index++];
      if (!fn) {
        res.statusCode = err ? 500 : 404;
        return res.end(err ? 'Server error' : 'Not found');
      }
      try {
        if (err && fn.length === 4) return fn(err, req, res, next); // error middleware
        if (!err && fn.length < 4) return fn(req, res, next);
        return next(err); // skip: wrong kind of function for this state
      } catch (thrown) {
        return next(thrown);
      }
    };
    next();
  };
  app.use = (fn) => stack.push(fn);
  return app;
}

const trace = [];
const app = createApp();

app.use((req, res, next) => { trace.push('timer: start'); res.on('finish', () => trace.push('timer: end')); next(); trace.push('timer: back after next'); });
app.use((req, res, next) => { trace.push('auth'); if (req.headers.authorization !== 'token-1') { res.statusCode = 401; return res.end('Unauthorized'); } next(); });
app.use((req, res, next) => { if (req.url === '/crash') throw new Error('bug'); next(); });
app.use((req, res) => { trace.push('handler'); res.end('Hello student'); });
app.use((err, req, res, next) => { trace.push('error handler: ' + err.message); res.statusCode = 500; res.end('Something went wrong'); });

const server = http.createServer(app);
server.listen(0, async () => {
  const base = 'http://127.0.0.1:' + server.address().port;
  const call = async (path, headers) => {
    trace.length = 0;
    const res = await fetch(base + path, { headers });
    const body = await res.text();
    await new Promise((r) => setImmediate(r));
    console.log(path.padEnd(7), res.status, body.padEnd(22), '|', trace.join(' > '));
  };
  await call('/', { authorization: 'token-1' });
  await call('/', {});
  await call('/crash', { authorization: 'token-1' });
  server.close();
});

Each request prints the status, body and the order in which the middleware ran, so the onion shape is visible. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): / 200 Hello student | timer: start > auth > handler > timer: back after next > timer: end / 401 Unauthorized | timer: start > auth > timer: back after next > timer: end /crash 500 Something went wrong | timer: start > auth > error handler: bug > timer: back after next > timer: end

Key points

  • Middleware has the shape (req, res, next).
  • Call next() to continue, or end the response.
  • Order is behaviour. Add functions in the right order.
  • Code after next() runs on the way out, like an onion.

Common mistakes

  • Forgetting to call next(), so the request hangs.
  • Calling next() after already sending the response, which causes errors.
  • Registering the 404 handler before the routes.
  • Putting the body parser after the route that needs it.

Follow-ups

  • How does Koa's await next() differ from Express next()?
  • Why do error handlers have four parameters in Express?
  • How would you apply middleware only to some routes?

Tips

  • Draw the onion and mark in and out.
  • State the three outcomes of a middleware: respond, next, error.
  • Mention that order is part of the behaviour.