How does koa-compose work?

IntermediateJavaScript interview questionBy , updated 24 November 2026

Short answer

koa-compose is the small function Koa uses to turn its array of middleware into one function. It calls the first middleware with a next that runs the second, and so on, each wrapped in a promise. Because await next() waits for everything downstream, code before it runs on the way in and code after it runs on the way out: the onion model.

What koa-compose is

When you call app.use(fn), Koa pushes fn onto an array. When the server starts handling requests, Koa passes that array to compose once and gets back a single function, fnMiddleware(ctx), which it calls for every request. Koa 3 even accepts a compose option in the Application constructor, so you can swap in your own.

The package is tiny and has no dependencies. As of late 2026 the version on npm's latest tag is 4.1.0, and that is what Koa 2 and Koa 3 install. The walk-through below is that published code. Middleware chaining is one of the patterns covered in design patterns in JavaScript, where it appears as chain of responsibility; this page goes into the one implementation interviewers ask about most. The place to practise it is Compose Koa-style async middleware with next().

The onion model

const log = [];
const run = compose([
  async (ctx, next) => { log.push("a in"); await next(); log.push("a out"); },
  async (ctx, next) => { log.push("b in"); await next(); log.push("b out"); },
]);

await run({});
// ["a in", "b in", "b out", "a out"]

Each middleware is a layer. The request passes inwards through every layer's "before" code, reaches the centre, then passes back out through every "after" code in reverse order. That is why a timing middleware in Koa is three lines: read the clock, await next(), read the clock again. The second reading happens after every inner middleware, including the route handler, has finished.

A middleware that never calls next() ends the chain. Nothing inside it runs, and the outer layers resume as soon as it returns.

The dispatch(i) implementation

function compose(middleware) {
  if (!Array.isArray(middleware)) throw new TypeError("Middleware stack must be an array!");
  for (const fn of middleware) {
    if (typeof fn !== "function") throw new TypeError("Middleware must be composed of functions!");
  }

  return function (context, next) {
    let index = -1; // the highest middleware index dispatched so far
    return dispatch(0);

    function dispatch(i) {
      if (i <= index) return Promise.reject(new Error("next() called multiple times"));
      index = i;
      let fn = middleware[i];
      if (i === middleware.length) fn = next;
      if (!fn) return Promise.resolve();
      try {
        return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
      } catch (err) {
        return Promise.reject(err);
      }
    }
  };
}

This mirrors the 4.1.0 source line for line. Walking through it:

  1. Validation happens once, when compose is called, not on every request. A non-array or a non-function entry throws a TypeError straight away.
  2. The returned function takes (context, next). So a composed stack is itself a middleware and can be nested inside another stack. Koa calls it with only ctx, so next is undefined at the top level.
  3. index lives in the closure of one call, so each request gets its own counter. It records the highest position dispatched so far.
  4. dispatch(i) picks the function to run. For positions inside the array it is middleware[i]. One past the end it is the outer next, which lets a nested stack hand control back to its parent. If there is nothing there, it returns Promise.resolve(), which is what makes the innermost await next() resolve.
  5. next for middleware i is dispatch.bind(null, i + 1). Calling it runs the next layer and returns that layer's promise, so await next() waits for the whole rest of the chain. The bind is just a way to fix the argument; see call, apply and bind.
  6. Promise.resolve(fn(...)) normalises the result. A plain function that returns undefined, or a value, still produces a promise, so callers can always await.
  7. The try/catch turns a synchronous throw into a rejection. Without it, a non-async middleware that throws would escape as an exception from dispatch instead of rejecting the promise its caller is awaiting.

The index guard

If middleware 0 calls next() once, dispatch(1) sets index to 1 and the chain continues. If it calls next() a second time, that is dispatch(1) again, 1 <= index is true, and the call returns a promise rejected with next() called multiple times. Running the downstream layers twice would send two responses or double-count work, so the guard fails loudly instead.

The master branch of koajs/compose holds a rewrite that has never been published. (A 4.2.0 that only adds array flattening was published and then deprecated on npm as breaking; latest is still 4.1.0.) The rewrite tracks a nextCalled flag per layer and, outside production, also throws when a middleware resolves before its downstream did, which catches a forgotten await. Interviewers expect the index version above.

Error propagation

Because every layer is a promise and each await next() awaits the inner ones, an error thrown deep inside rejects every promise on its way back out. Any outer layer can catch it by wrapping await next():

const errors = async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.status ?? 500;
    ctx.body = { message: err.expose ? err.message : "Internal error" };
  }
};

app.use(errors); // registered first, so it is the outermost layer

Put the error layer first so it wraps everything. If nothing catches, fnMiddleware(ctx) rejects and Koa's own .catch hands the error to ctx.onerror, which sets the status and emits an error event on the app.

The classic bug is calling next() without await or return. The middleware's promise then resolves at once, the outer layers carry on before the inner ones have finished, and an inner rejection is no longer caught by the outer try. The promises versus async/await answer covers why the missing await detaches the chain.

How it differs from Express

Express also passes a next, but it is a callback that returns nothing useful. Calling next() starts the next handler; it does not tell you when that handler has finished. So Express middleware cannot run code "on the way out" with an await; the usual workaround is listening for the response's finish event.

Errors travel differently too. In Express you call next(err) and the router skips to error-handling middleware, which is recognised by having four parameters, (err, req, res, next). Express 5 added one bridge: if a handler returns a promise that rejects, the router calls next(err) for you. It still does not let you await downstream handlers. In Koa there are no special error handlers, just try/catch around await next().

The same pattern on the frontend

Redux middleware has the same shape, store => next => action, but it is synchronous: code before next(action) runs before the reducers, code after it sees the new state. What is Redux middleware covers the chain applyMiddleware builds with reduceRight.

Fetch interceptors follow it too. fetch has no interceptor API, so apps wrap it, and an onion is a clean way to do that. Each layer can change the request before next() and inspect or retry the response after it:

const withAuth = async (req, next) => {
  req.headers.set("Authorization", `Bearer ${getToken()}`);
  const res = await next();
  if (res.status === 401) onSignedOut();
  return res;
};

const withTiming = async (req, next) => {
  const start = performance.now();
  const res = await next();
  console.debug(req.url, Math.round(performance.now() - start), "ms");
  return res;
};

const send = (req) => compose([withAuth, withTiming])(req, () => fetch(req));

The second argument does the real work: it is the outer next that dispatch calls one past the end of the array. Each layer returns the inner promise so the response flows back out. The same idea in Axios form is practised in Implement request and response interceptors similar to Axios.

Angular's functional HTTP interceptors and the async version of compose in Implement composeAsync() and pipeAsync() are close relatives.

Follow-up questions interviewers ask

Why does koa-compose need the index guard at all?

A middleware can call next() twice by mistake, for example in both a try and a catch. The downstream layers would run twice on the same request. The guard turns that into a clear rejection.

Why wrap the call in Promise.resolve if middleware is async?

Middleware does not have to be async. A plain function returns a value or undefined, and Promise.resolve makes it awaitable, so the chain behaves the same whatever each layer returns.

Could you write it with reduceRight like Redux?

Yes: start from the innermost layer and wrap outwards, each step closing over the one inside it. You then need a flag per layer to catch double next() calls and your own try/catch for sync throws. The recursive dispatch(i) gets both from one counter and builds each next only when it is called.

What happens if the last middleware calls next()?

dispatch reaches one past the end, uses the outer next if one was passed, and otherwise returns Promise.resolve(). So await next() in the last layer simply resolves.

How would you stop the chain early?

Do not call next(). Set the response and return. The outer layers still run their "after" code.

Practise it in code

Interviewers rarely stop at the definition. These questions open in an editor with tests.

  1. Compose Koa-style async middleware with next()Medium30 min
  2. Implement Redux createStore() with enhancers and applyMiddleware(): middleware order, thunk and loggerMedium45 min
  3. Implement request and response interceptors similar to AxiosMedium45 min
  4. Implement composeAsync() and pipeAsync() with chainable pipe, tap and catchMedium30 min
  5. Implement compose() and pipe()Medium35 min