The Chain of Responsibility Pattern in JavaScript, With Examples
The chain of responsibility pattern passes a request along handlers until one deals with it. See middleware, validation chains and support tiers in JavaScript.

The chain of responsibility pattern passes a request along a line of handlers, each of which either deals with it or hands it to the next. The sender does not know which handler will act, and the handlers do not know about each other beyond "the next one". If you have written Express or Koa middleware, you have used it daily: a request travels through logging, body parsing, authentication and routing, and any step can answer early or pass the request on. This post builds the pattern from scratch in JavaScript on Node.js 24, first as a linked list of handlers, then as an array pipeline with next, then an async middleware runner like Koa's, and covers short-circuiting, error handling, ordering and the places the pattern misleads. Every sample prints its output.
The problem: a growing if-else
A support system routes tickets by severity. The naive version is one function with a ladder of conditions.
function route(ticket) {
if (ticket.severity === "low" && ticket.topic === "billing") return "billing bot";
if (ticket.severity === "low") return "faq bot";
if (ticket.severity === "high" && ticket.vip) return "account manager";
if (ticket.severity === "high") return "senior agent";
return "unassigned";
}
console.log(route({ severity: "low", topic: "billing" }));
console.log(route({ severity: "high", vip: true }));billing bot
account managerEvery new rule edits this function, order matters and nothing separates the rules, so a conflict between two of them is hidden in the ordering. The chain turns each rule into its own handler.
A linked chain
Each handler decides whether it can handle the request. If not, it delegates to the next.
class Handler {
#next = null;
setNext(handler) {
this.#next = handler;
return handler;
}
handle(ticket) {
if (this.canHandle(ticket)) return this.process(ticket);
if (this.#next) return this.#next.handle(ticket);
return "unassigned";
}
}
class BillingBot extends Handler {
canHandle(t) {
return t.severity === "low" && t.topic === "billing";
}
process() {
return "billing bot";
}
}
class FaqBot extends Handler {
canHandle(t) {
return t.severity === "low";
}
process() {
return "faq bot";
}
}
class AccountManager extends Handler {
canHandle(t) {
return t.severity === "high" && t.vip;
}
process() {
return "account manager";
}
}
class SeniorAgent extends Handler {
canHandle(t) {
return t.severity === "high";
}
process() {
return "senior agent";
}
}
const first = new BillingBot();
first.setNext(new FaqBot()).setNext(new AccountManager()).setNext(new SeniorAgent());
console.log(first.handle({ severity: "low", topic: "billing" }));
console.log(first.handle({ severity: "low", topic: "shipping" }));
console.log(first.handle({ severity: "high", vip: true }));
console.log(first.handle({ severity: "high" }));
console.log(first.handle({ severity: "medium" }));billing bot
faq bot
account manager
senior agent
unassignedEach rule is a class, and the order is visible where the chain is built. The setNext method returns the next handler so the chain reads left to right. The default unassigned is the answer when the end of the chain is reached without a taker. Adding a rule means adding a class and splicing it in, without editing any other handler.
The lighter form: an array of functions
In JavaScript you rarely need classes. A handler can be a function that returns a result or undefined to mean "not mine".
const handlers = [
(t) => (t.severity === "low" && t.topic === "billing" ? "billing bot" : undefined),
(t) => (t.severity === "low" ? "faq bot" : undefined),
(t) => (t.severity === "high" && t.vip ? "account manager" : undefined),
(t) => (t.severity === "high" ? "senior agent" : undefined),
];
const route = (ticket) => handlers.map((h) => h(ticket)).find((r) => r !== undefined) ?? "unassigned";
console.log(route({ severity: "high", vip: true }));
console.log(route({ severity: "medium" }));account manager
unassignedThat version runs every handler, since map is eager. To stop at the first match, use a loop, which is closer to the true pattern.
function firstMatch(handlers, input) {
for (const handler of handlers) {
const result = handler(input);
if (result !== undefined) return result;
}
return undefined;
}
const calls = [];
const handlers = [
(t) => (calls.push("a"), undefined),
(t) => (calls.push("b"), "handled by b"),
(t) => (calls.push("c"), "handled by c"),
];
console.log(firstMatch(handlers, {}));
console.log(calls);handled by b
[ 'a', 'b' ]The third handler never ran. Stopping early is what makes this a chain and not a broadcast. A broadcast calls everyone, and the observer pattern covers that.
Middleware: handlers that can act and pass on
In middleware chains, a handler does not necessarily consume the request. It may do some work, such as logging, then call next() to continue, and it may do more work after the rest of the chain returns. Here is a minimal runner.
function compose(middlewares) {
return function run(context) {
let index = -1;
function dispatch(i) {
if (i <= index) throw new Error("next() called twice");
index = i;
const fn = middlewares[i];
if (!fn) return;
return fn(context, () => dispatch(i + 1));
}
return dispatch(0);
};
}
const log = [];
const app = compose([
(ctx, next) => {
log.push(`start ${ctx.path}`);
next();
log.push(`end ${ctx.status}`);
},
(ctx, next) => {
if (!ctx.user) {
ctx.status = 401;
return; // short-circuit: do not call next
}
next();
},
(ctx) => {
ctx.status = 200;
},
]);
app({ path: "/profile", user: "ada" });
app({ path: "/profile", user: null });
console.log(log);[ 'start /profile', 'end 200', 'start /profile', 'end 401' ]The second middleware returned without calling next, so the third never ran for the anonymous request, and the first one's "after" code still ran on the way back out. That "onion" shape, where each layer wraps the rest, is how Koa works, and Express is close to it. The check i <= index catches a middleware calling next() twice, which would run the rest of the chain twice.
Async middleware
Real middleware awaits things. The change is small: dispatch returns a promise and middleware await next().
function compose(middlewares) {
return (context) => {
let index = -1;
const dispatch = async (i) => {
if (i <= index) throw new Error("next() called twice");
index = i;
const fn = middlewares[i];
if (!fn) return;
await fn(context, () => dispatch(i + 1));
};
return dispatch(0);
};
}
const timing = async (ctx, next) => {
ctx.trace.push("timing in");
await next();
ctx.trace.push("timing out");
};
const load = async (ctx, next) => {
ctx.user = await Promise.resolve({ id: 1, name: "Ada" });
await next();
};
const handler = async (ctx) => {
ctx.trace.push(`hello ${ctx.user.name}`);
};
const failing = async () => {
throw new Error("database down");
};
const ctx = { trace: [] };
await compose([timing, load, handler])(ctx);
console.log(ctx.trace);
const errCtx = { trace: [] };
try {
await compose([timing, failing])(errCtx);
} catch (err) {
console.log(err.message, errCtx.trace);
}[ 'timing in', 'hello Ada', 'timing out' ]
database down [ 'timing in' ]An error thrown deep in the chain rejects the promises up the stack, so an outer middleware can catch it with try and await next(). Note that timing out never ran for the failing request, because the error bypassed it. If cleanup must always run, put it in a finally. Error-handling middleware is therefore conventionally placed first, so it wraps everything.
A validation chain
Chains also fit validation, where each handler checks one thing and the first failure stops the process.
const checks = [
(order) => (order.items.length ? null : "order has no items"),
(order) => (order.items.every((i) => i.qty > 0) ? null : "quantities must be positive"),
(order) => (order.total <= order.creditLimit ? null : "total exceeds credit limit"),
];
function validate(order) {
for (const check of checks) {
const error = check(order);
if (error) return { valid: false, error };
}
return { valid: true };
}
console.log(validate({ items: [{ qty: 2 }], total: 50, creditLimit: 100 }));
console.log(validate({ items: [{ qty: 0 }], total: 50, creditLimit: 100 }));
console.log(validate({ items: [], total: 0, creditLimit: 100 }));{ valid: true }
{ valid: false, error: 'quantities must be positive' }
{ valid: false, error: 'order has no items' }Order matters for the cheap checks first, and for correctness: the credit check assumes items exist. If you want every error reported at once, collect them instead of stopping, which turns the chain into a composite of rules.
Pitfalls
Nobody handles it. If the end of the chain is reached with no handler, decide on the outcome: a default, an error or
undefined. Silent drops are the classic bug.Order dependence. The chain's behavior is the order of its handlers, so document it and test the order, for example that authentication runs before authorization.
Hidden control flow. Reading code that sets
ctx.userthree middlewares earlier is hard. Keep the context object's shape documented and the chain short enough to read in one screen.**Calling
next()twice** or forgetting to call it, which stalls the request. Theindexguard above catches the first, and a timeout or test catches the second.Shared mutable context. Every handler can change it. Prefer adding fields over rewriting them.
Where the advice stops
A switch or a lookup table is simpler when the decision is one choice among several known cases and no handler needs to act and pass on. The chain pays off when handlers are independent and reorderable, when new ones arrive by configuration or plugin or when each handler wraps the next, as in middleware. For two or three fixed conditions, a plain if is clearer.
Testing a chain
Test each handler alone first. A handler is a function from a request to a result or a pass, so tests are tables of inputs and expected outcomes, including the inputs that should pass through. Then test the assembled chain on a few requests that exercise the order: one that should be taken by an early handler, one that falls through to a late one and one that nobody takes. That last test pins the default behavior and protects you from the silent-drop bug. When the chain is built from configuration, add a test that loads the real configuration and checks the handler order, because a reordered line in a config file is an easy mistake to make and a hard one to notice.
Chains in the wild
Beyond Express and Koa, the shape appears in many places. Event bubbling in the DOM sends an event up through parent elements until a handler calls stopPropagation(). Exception handling is a chain: the runtime walks up the call stack looking for a catch that can handle the error. Logging libraries pass a message through transports that may filter it. Build tools pass a file through a list of loaders or plugins, each of which may transform it. Recognizing these helps you borrow their conventions, such as a clear way to say "I handled it, stop" and a clear way to say "not mine, continue".


