Back to results for “Express & Middleware”
Node.js › Architecture & Design Patterns

What is the Middleware (Chain of Responsibility) pattern as implemented by Express, and how does the 'next()' function drive it?

Intermediate

Answer

Express middleware implements the Chain of Responsibility pattern: each middleware function receives the request, response, and a 'next' callback, and can either handle the request completely, modify it and pass control to the next function in the chain by calling next(), or short-circuit the chain by sending a response directly -- this lets cross-cutting concerns (authentication, logging, error handling) be composed as small, independent, reorderable functions rather than one large monolithic handler.
app.use((req, res, next) => {
  console.log(`${req.method} ${req.path}`);
  next(); // pass control to the next middleware in the chain
});

app.use((req, res, next) => {
  if (!req.headers.authorization) return res.status(401).end(); // short-circuits the chain
  next();
});
Real-world example An API composes a request-logging middleware, an authentication middleware, and a rate-limiting middleware as three separate, independently testable functions applied in sequence, rather than combining all three concerns into a single large function at the top of every route handler.

Common follow-ups: What happens if a middleware function neither calls next() nor sends a response?;How does error-handling middleware (with four parameters) fit into this same chain-of-responsibility model?