Chain of Responsibility

Pipeline de middleware

Escrito por Darjus Kazakevic · revisado el

The pattern inside every middleware stack.

Every HTTP request passes several checks: logging, rate limiting, authentication, body parsing. Written inline, they nest inside each other, and the order, which decides the behaviour, is hidden in the code.

Chain of Responsibility gives each check its own handler with one choice: answer the request, or call next(). Express, Koa and Hono middleware all work this way. In TypeScript a handler is just a function (req, next) => Response, and the chain is an array.

En esencia — Pass a request through a list of handlers, each free to act, pass it on or stop it, so the pipeline is a list you can read, not nested ifs.

Cuándo recurrir a él

Recurre a él cuando

  • A request passes several checks, such as auth and rate limits, in order
  • Steps get added or reordered without opening the others
  • Different routes need different subsets of the same checks

Reconsidéralo cuando

  • Exactly one handler always answers, and you know which up front
  • A fixed two-step flow that reads more clearly as two calls
  • Steps that share a lot of state: write one function instead

Conceptos clave

Handler
A function that receives the request and a next() callback. It can answer and stop, call next() and pass on, or wrap next() to work before and after it.
next()
The call that passes control to the rest of the chain. Not calling it stops the chain. Awaiting it lets a handler see the response, for timing or headers.
The chain
An ordered list of handlers folded into one function. The array order is the run order, so a reviewer reads the pipeline from top to bottom.
Final handler
The last step, usually the route itself or a 404. It gives a request that passed every check a deliberate answer.

Reglas de diseño

The order is the behaviour: keep it in one list
A rate limiter placed after authentication never sees failed logins, so password guessing goes unlimited. Build the whole chain in one array, so the order is reviewed as a diff.
One check per handler
Auth, rate limiting and logging are separate handlers. A handler that does two jobs cannot be reordered or removed alone, which is the main reason to use a chain.
End the chain with a deliberate final handler
If every handler may pass, some request will pass them all. End with an explicit route or a 404, so reaching the end is a chosen answer, not an undefined response.

Errores habituales

  • Rate limiting placed after authentication, so failed login attempts are never limited.
  • A handler that forgets to return next(), so the request hangs or gets an empty response.
  • Calling next() twice, for example in a retry, which runs the rest of the chain twice.
  • No final handler, so a request that passes every check gets an undefined response.