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?
IntermediateAnswer
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.