Pattern 18/22 · Behavioral

Chain of Responsibility

Pass a request through a series of handlers: each one either answers it and stops the chain, or calls `next` to push it along. Whoever sends the request doesn't need to know who will handle it.

Behavioral●●○14 min read8 stepsalso known as: Chain of Command, Pipeline, Middleware
middlewarepipelineinterceptorvalidatebehavioralpluginnext

01 — It starts with code that is breaking

Problem

You have POST /api/orders. Six months in, it contains, in this exact order: verify the JWT, check the token hasn't expired, rate-limit by IP, validate the body with zod, check the user has rights on that shop, and finally the business logic. All in one 120-line handler, with the actual business logic sitting at the bottom of the function.

Those six steps have completely different lifecycles. rateLimit changes every time the anti-spam policy changes. permission changes every time a role is added. payload changes every time a field is added. But they share one function, so every change to one means scrolling past the other five — and the git blame on this function has your name on it for six months straight.

Then a second route shows up: PATCH /api/orders/:id needs four of the six steps, in a different order, plus one of its own. You copy-paste. When you find a race condition in rateLimit, you fix one file and then have to hunt down the other eleven copies in the repo — three of which were hand-edited long ago.

It's worse than a regular if/else: each step here decides for itself whether the request may continue, and those decisions are scattered. Nowhere declares "this route runs these steps, in this order". To find out whether /api/orders is rate-limited, you have to read all 120 lines.

The real problem: the list of steps, their order, and the "stop or continue" logic are hard-coded at the call site, even though they're independent business concerns that vary per route. Chain of Responsibility pulls exactly those three things apart.

02 — The idea, before touching code

Solution

Each check becomes an independent handler that knows exactly two things: answer the request itself (return a result, the chain stops here), or call next(ctx) to push the context on to the next handler. A handler takes no "which step am I" parameter, never calls another handler directly, and doesn't know who comes before or after it.

The "who comes after whom" part lives somewhere else: the runner that assembles the chain. It holds the order and creates the next function the handler receives. So adding a new step = writing one more function + adding one name to the list; no existing handler gets edited. And to see what a route runs, you read the list, not 120 lines.

In TypeScript you don't need a class for this. A handler is function (ctx, next). The pattern is so familiar you write it daily: Express/Koa/Nuxt middleware, axios interceptors, stopPropagation() on DOM events. Chain of Responsibility isn't exotic — it's the formal name for what you already call "middleware".

03 — Doing it for real, one code fragment per step

Step by step

1

Spot the chain: look for "if it's fine, carry on"

The signal isn't "lots of ifs". The signal is a sequence of guard clauses, each checking a different concern, and each with the power to block the request. If you catch yourself writing "no JWT returns 401, more than 60 requests returns 429, bad body returns 400..." — that's a chain waiting to be born.

Write out the ugly version first. It isn't wrong yet; it just isn't split up.

tsorders-handler-v1.ts
export async function createOrder(req: Request, res: Response) {
  const user = verifyJwt(req.headers.authorization ?? '')
  if (!user) return res.status(401).json({ error: 'unauthorized' })

  if (!limiter.tryTake(req.ip)) return res.status(429).json({ error: 'rate limited' })

  const parsed = orderSchema.safeParse(req.body)
  if (!parsed.success) return res.status(400).json(parsed.error)

  if (!(await canManage(user, parsed.data.shopId)))
    return res.status(403).json({ error: 'forbidden' })

  // ... 90 lines of business logic at the bottom, the hardest thing on earth to test
}
Six concerns, one function, one file. Every new feature will wedge another if in here.
Key pointChain of Responsibility is worth considering when the steps are independent but share one flow, and any step may end the game.
2

Write the handler contract: `(ctx, next)`

All the abstraction in this pattern fits in three lines of types. A Handler takes a context and a next function and returns the final result. That alone is enough for a handler to block the chain (don't call next) or let it through (call next).

ctx is the shared memory that travels down the chain: the input data, plus a place where later handlers read what earlier ones produced. Without ctx, handlers would have to call verifyJwt again — wasteful and prone to drift.

tshandler.ts
export type Ctx = {
  token: string
  ip: string
  route: string
  body: unknown
  hits: number
  user?: { id: string, role: string }
  order?: { shopId: string }
}

export type Next = (ctx: Ctx) => string
export type Handler = (ctx: Ctx, next: Next) => string
The shared contract. handler.ts imports no other handler — that's the whole reason the chain can be assembled.
Key pointA handler depends only on a type, never on a concrete handler. Dependency Inversion, the cheap and effective edition.
3

Write handlers: either answer, or `next(ctx)`

One responsibility per handler, a single if block. Two exits: return a string (stop) or call next (continue). There is no third exit.

Notice the handler has no idea rateLimit exists. All it knows is "call next and the flow continues". That's the core difference from a function that calls steps in sequence: here, the power to decide order is taken out of the handler's hands.

tshandlers.ts
export const auth: Handler = (ctx, next) => {
  if (!ctx.token) return '401 not logged in'   // answers itself -> chain stops
  return next(ctx)                             // no opinion -> carry on
}

export const rateLimit: Handler = (ctx, next) => {
  if (ctx.hits > 2) return '429 over quota ' + ctx.ip
  return next(ctx)
}

export const payload: Handler = (ctx, next) => {
  if (ctx.body === '') return '400 empty payload'
  return next(ctx)
}

export const permission: Handler = (ctx, next) => {
  if (ctx.route === '/admin' && ctx.user?.role !== 'root') return '403 forbidden'
  return next(ctx)
}
Key pointTesting a handler means calling it with a fake next: auth(ctx, () => "PASSED"). No chain, no server.
4

The runner assembles the chain — the only place that knows the order

The runner holds the handler array and an index. It calls the first handler, and each time a handler calls next, the runner calls the next one. This is effectively Composite: a single handler and a whole chain have the same shape, (ctx) => string, so you can nest them.

The recursive version below is the easiest to read. In real code with state, you'll want to add a visited array to log which chain actually ran — otherwise debugging a 403 response becomes an afternoon of guesswork.

tschain.ts
export function dispatch(handlers: Handler[], i: number, ctx: Ctx): string {
  if (i === handlers.length) return '200 OK ' + ctx.route  // nobody left -> business logic
  return handlers[i](ctx, cc => dispatch(handlers, i + 1, cc))
}

export const orderChain: Handler[] = [auth, rateLimit, payload, permission]

export const handleOrder = (ctx: Ctx) => dispatch(orderChain, 0, ctx)
handlers[i](ctx, cc => dispatch(handlers, i + 1, cc)) — that one line is the entire pattern.
Key pointOrder is data (an array), not code. Changing the order = changing the array, without touching a single handler.
5

Run it and look at the trace

Four handlers, five requests. The right-hand column is the chain that actually ran — that's what you'll want in real logs, because it instantly answers "where was this request blocked?".

Look at the third request: it dies at rate-limit and never runs payload. That's the real value of this pattern, not decoration: cheap steps run first, so expensive steps (DB queries, API calls) aren't called for nothing.

tsmain.ts
function send(user: string, route: string, body: string, hits: number) {
  visited.length = 0
  const res = dispatch(0, { user, ip: '10.0.0.7', route, body, hits })
  console.log(res.padEnd(28) + '| ran: ' + visited.join(' -> '))
}

send('', '/posts', 'hello', 1)
send('lam', '/posts', '', 1)
send('lam', '/posts', 'hello', 5)
send('lam', '/admin', 'x', 1)
send('root', '/admin', 'x', 1)
console
401 not logged in           | ran: auth
400 empty payload           | ran: auth -> rate-limit -> payload
429 over quota 10.0.0.7     | ran: auth -> rate-limit
403 forbidden               | ran: auth -> rate-limit -> payload -> permission
200 OK /admin               | ran: auth -> rate-limit -> payload -> permission
6

Handlers can modify the context, or redirect instead of rejecting

A handler isn't limited to "block or pass". It can write results into ctx for later handlers: auth attaches the user, payload attaches the parsed object. Returning next({ ...ctx, user }) instead of next(ctx) is all it takes — later handlers don't know who wrote the data.

It can also redirect instead of blocking: for an unauthenticated request, 302 /login is friendlier to browsers than 401. This is where CoR parts ways with a plain validation list: each step gets to decide the request's fate.

tshandlers-v2.ts
export const auth: Handler = (ctx, next) => {
  const user = verifyJwt(ctx.token)
  if (!user) return '302 /login'        // redirect, don't block
  return next({ ...ctx, user })         // later handlers can read ctx.user
}

export const payload: Handler = (ctx, next) => {
  const parsed = orderSchema.safeParse(ctx.body)
  return parsed.success
    ? next({ ...ctx, order: parsed.data })  // parse ONCE, the whole chain uses it
    : '400 invalid payload'
}
Key pointIf a later handler has to recompute something an earlier one already computed, your ctx is missing a field.
7

The class version with `setNext`: when handlers need state or dynamic wiring

The function version covers 90% of needs. But when a handler has its own config (allowed origins, per-tenant limits), or when you want to link pairs instead of declaring an array, the classic class version has its place.

A small GoF trick: setNext returns the handler that was just attached, so you can chain a.setNext(b).setNext(c) instead of three separate lines.

tsmiddleware-class.ts
abstract class Middleware {
  private nextMw: Middleware | null = null

  setNext(mw: Middleware): Middleware {
    this.nextMw = mw
    return mw                      // enables a.setNext(b).setNext(c)
  }

  protected then(ctx: Ctx): string {
    return this.nextMw ? this.nextMw.handle(ctx) : '200 OK ' + ctx.route
  }

  abstract handle(ctx: Ctx): string
}

class CorsMiddleware extends Middleware {
  constructor(private allowed: string[]) { super() }

  handle(ctx: Ctx): string {
    if (!this.allowed.includes(ctx.origin)) return '403 origin blocked'
    return this.then(ctx)
  }
}
Key pointUse a class when a handler has its own config or must be linked at runtime. Otherwise, functions + an array are leaner and easier to test.
8

Build chains from config — and the price of order being data

When each route needs a different set of steps, and that list comes from admin/DB/tenant config, you build the chain from names, not from code. New route, new gate, a customer's plugin: the runner stays untouched.

But here's the flip side: order is data, and TypeScript can't check data. Put permission before auth and every request gets a 403 while the compiler stays perfectly silent. Config-built chains must have tests (assert the order first), and should reject unknown names at chain-build time rather than silently skipping them.

tsregistry.ts
const registry: Record<string, Handler> = { auth, rateLimit, payload, permission, cors }

export function buildChain(names: string[]): Handler[] {
  return names.map((n) => {
    const h = registry[n]
    if (!h) throw new Error('Unknown handler: ' + n)   // fail early, not silently
    return h
  })
}

// regular route:  buildChain(['auth', 'payload'])
// admin route:    buildChain(['auth', 'rateLimit', 'payload', 'permission'])
With async, next returns a Promise: Koa writes await next() (in from the outside, out from the inside), Express uses next(err) to jump to the error chain — a second chain running in parallel.
Key pointTest chains like you test config: one test asserting "every chain in the registry has auth before permission" is far cheaper than a site-wide 403 incident.

04 — Who talks to whom

Structure

  • HandlerOne step. Either answers itself (chain stops) or calls `next(ctx)` to pass it on. Doesn't know other handlers exist.
  • ConcreteHandler`auth`, `rateLimit`, `payload`, `permission`. One concern each, one file, one if block.
  • ContextData traveling down the chain: the initial input + whatever each handler writes for the ones after it.
  • RunnerHolds the handler array and index, creates `next`. The only place that knows the chain's structure.
  • ClientPicks a chain per route/request type, usually as a list of names read from config.
  Client ──handle(ctx)──► Runner (holds the order, creates next)
                              │
                              ▼
                        ┌───────────┐  ctx.user === null
                        │   auth    │ ───► '401 ...'  (stop)
                        └─────┬─────┘
                              │ next(ctx)  "I have no opinion"
                              ▼
                        ┌────────────┐
                        │ rate-limit │ ───► '429 ...'  (stop)
                        └─────┬──────┘
                              │ next(ctx)
                              ▼
                        ┌─────────┐
                        │ payload │ ───► '400 ...'    (stop)
                        └─────┬───┘
                              │ next({ ...ctx, order })
                              ▼
                        ┌────────────┐
                        │ permission │ ───► '403 ...'  (stop)
                        └─────┬──────┘
                              │ next(ctx)
                              ▼
                       '200 OK /orders'   <- nobody left, now business logic

05 — Edit freely, run it right here

Try it: four validators, whoever has an opinion answers

tsdemo.ts
type Ctx = { user: string, ip: string, route: string, body: string, hits: number }
type Next = (c: Ctx) => string
type Handler = (c: Ctx, next: Next) => string

const visited: string[] = []
const mark = (name: string) => { visited.push(name) }

const auth: Handler = (c, next) => {
  mark('auth')
  return c.user === '' ? '401 not logged in' : next(c)
}
const rateLimit: Handler = (c, next) => {
  mark('rate-limit')
  return c.hits > 2 ? '429 over quota ' + c.ip : next(c)
}
const payload: Handler = (c, next) => {
  mark('payload')
  return c.body === '' ? '400 empty payload' : next(c)
}
const permission: Handler = (c, next) => {
  mark('permission')
  return c.route === '/admin' && c.user !== 'root' ? '403 forbidden' : next(c)
}

const chain: Handler[] = [auth, rateLimit, payload, permission]

function dispatch(i: number, c: Ctx): string {
  if (i === chain.length) return '200 OK ' + c.route
  return chain[i](c, cc => dispatch(i + 1, cc))
}

function send(user: string, route: string, body: string, hits: number) {
  visited.length = 0
  const res = dispatch(0, { user, ip: '10.0.0.7', route, body, hits })
  console.log(res.padEnd(28) + '| ran: ' + visited.join(' -> '))
}

send('', '/posts', 'hello', 1)
send('lam', '/posts', '', 1)
send('lam', '/posts', 'hello', 5)
send('lam', '/admin', 'x', 1)
send('root', '/admin', 'x', 1)
console
401 not logged in           | ran: auth
400 empty payload           | ran: auth -> rate-limit -> payload
429 over quota 10.0.0.7     | ran: auth -> rate-limit
403 forbidden               | ran: auth -> rate-limit -> payload -> permission
200 OK /admin               | ran: auth -> rate-limit -> payload -> permission

The same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.

06 — Honest about the cost

When to use it, when not to

Use it when

  • Several independent checks/transforms apply to the same request, and cheap steps should block early so expensive ones never have to run.
  • The sender shouldn't know (or isn't allowed to know) who handles the request: gateways, SDKs, plugin systems, third-party integrations.
  • Each route/request type needs a different set of steps, or the chain has to be assembled dynamically from config, DB, feature flags, tenant.
  • You need to add/remove a step without editing old code — the Open/Closed Principle in its most visible form.
  • There are several different ways to answer (401, 429, 302, cache hit), and which one to take is a local decision for each step.

Don't use it when

  • Over-engineering. Two fixed checks, one route, nobody else using it? Write two if lines and go do something else. A chain only pays off with ≥ 4 steps, or when the order varies by route, or when whoever assembles the chain isn't whoever writes the handlers.
  • Harder debugging: the bug lives in the fourth handler but shows up in the final response. Log the list of handlers that ran for every request from day one, don't wait for an incident.
  • Order is data, and TS can't check it. permission before auth = site-wide 403. Test your chains, and fail early on handler names that don't exist.
  • A handler forgets to call next (request hangs) or calls next twice (business logic runs twice). In Express, forgetting next(err) inside a catch lets the error fall through to the business handler — the error chain is a second chain, and you have to wire it up.
  • Every handler is another layer of nesting. Koa's await next() keeps the stack of everything downstream in a closure: dropping a heavy handler (big parse, DB query) into the middle of the chain slows down every request that passes through, including those blocked right after it.

07 — You have met it already, just not by name

In real code

Express / Koa / Nuxt middleware

Express: app.use((req, res, next) => ...), and next(err) jumps to the error-handler chain. Koa: async (ctx, next) => { ...; await next() } — the clearest view of the chain's "in-out" shape. Nuxt server middleware (defineEventHandler) and route middleware (defineNuxtRouteMiddleware + navigateTo) share the same structure: answer it yourself, or let it through.

axios interceptors

axios.interceptors.request.use(...) and .response.use(ok, err) line up into a chain: attach the auth header, refresh the token on 401, retry, normalize errors. When an interceptor rejects the Promise, the rest of the chain gets skipped — exactly the "stop the chain" semantics.

DOM event bubbling

Here the chain is the DOM tree itself: the event travels from a node up to its parents, and every node with a listener is a handler. event.stopPropagation() is the next() that never gets called; event.defaultPrevented is "someone already answered, the rest of you take the hint".

Error-handling chains

Nested try/catch: an exception looks for the nearest catch and stops there. Promise .catch() is the same — a rejection propagates to the nearest .catch, skipping the .thens in between. That's CoR for errors, and it explains why one .catch at the end of a chain catches every error above it.

08 — Try it yourself

Exercise

Write an `idempotency` handler for the order-processing chain: if the `idempotency-key` header has been seen before, return the old result **immediately** without running the handlers after it. If it hasn't been seen, carry on and store the result. Explain why it must come before the handler that writes to the DB.

Hints, open them one at a time:

  1. What else can a handler do with next besides calling it once? (Hint: call it and use the return value.)
  2. Where does the handler's own state (a Map of key -> response) live? A closure is enough, no class needed.
  3. What should happen when there's no header? Don't block — just next(ctx).

This handler wraps next: read the key; if it's cached, return right away (the chain stops, the DB is never hit); otherwise call next(ctx) once, store the result in the Map, and return it. It has to come before the DB-writing handler because its whole purpose is to guarantee the downstream part runs at most once per key — put it after the DB and the write has already happened before it can block anything.

tsexercise.ts
const seen = new Map<string, string>()

export const idempotency: Handler = (ctx, next) => {
  const key = ctx.headers['idempotency-key']
  if (!key) return next(ctx)          // no key -> no opinion

  const cached = seen.get(key)
  if (cached) return 'REPLAY ' + cached   // stop: the downstream part (DB) doesn't run

  const res = next(ctx)               // carry on EXACTLY once
  seen.set(key, res)
  return res
}

// chain: ['idempotency', 'auth', 'payload', 'createOrder']
// call twice with the same key -> 'REPLAY ...', createOrder runs only once

09 — Read them in pairs to see the essence

Related patterns

  • StrategyStrategy: the caller **picks** an algorithm and runs it, knowing what it picked. CoR: nobody picks; the request flows on its own and any handler that doesn't care passes it along.
  • DecoratorBoth nest, but a decorator **always** runs and wraps to add behavior; a CoR handler **may refuse** and cut the chain. The moment a handler runs code both before and after `next()`, that part is a decorator.
  • ObserverObserver is a broadcast: every subscriber runs. CoR is a pipeline: usually only one handler answers and the rest are skipped.
  • CommandThey often come as a pair: middleware (CoR) decides *whether it may run*, the command is *the thing that runs*. Recording the commands that pass through the chain enables replay, audit, retry.