Chain of Responsibility - Request Processing Pipelines
Learn the Chain of Responsibility pattern for building request processing pipelines. TypeScript examples for middleware, validation chains, and event handling.
Detailed Explanation
Chain of Responsibility Pattern
The Chain of Responsibility pattern links handlers into a chain and passes requests along the chain until one handler processes it. Each handler decides either to process the request or to pass it to the next handler.
Building the Chain
abstract class Middleware {
private next: Middleware | null = null;
linkWith(next: Middleware): Middleware {
this.next = next;
return next; // enables chaining: a.linkWith(b).linkWith(c)
}
handle(request: Request): Response | null {
if (this.next) return this.next.handle(request);
return null;
}
}
class AuthMiddleware extends Middleware {
handle(request: Request) {
if (!request.headers.get("Authorization")) {
return new Response("Unauthorized", { status: 401 });
}
return super.handle(request);
}
}
Express.js Middleware
The most famous implementation of Chain of Responsibility in JavaScript is Express.js middleware. Each app.use() adds a handler to the chain, and next() passes the request to the next handler:
app.use(logger); // logs request
app.use(authenticate); // checks auth token
app.use(rateLimit); // checks rate limits
app.use(router); // handles the actual request
Variations
- Linear chain: Each handler has exactly one successor.
- Tree chain: Handlers can delegate to multiple successors (like DOM event bubbling).
- Terminating vs non-terminating: Some chains stop at the first handler that can process the request; others let every handler process the request (like event listeners).
Error Handling
A well-designed chain includes error handling middleware at the end that catches and formats errors from any earlier handler. This is exactly how Express.js error middleware works.
Use Case
Chain of Responsibility is the foundation of HTTP middleware stacks (Express, Koa, Fastify), input validation chains (check format, then range, then business rules), logging pipelines with severity levels, technical support escalation systems, and DOM event bubbling/capturing.