koa-compose

Composes an array of Koa middleware functions into a single middleware function, enabling middleware groups and reusable stacks.

Since Koa 2 Spec ↗

Syntax

import compose from 'koa-compose';
const combined = compose([fn1, fn2, fn3]);
app.use(combined);

Parameters

NameTypeRequiredDescription
middleware Array<AsyncFunction> Yes An array of Koa-compatible async middleware functions `(ctx, next) => Promise<void>`. Executed in array order.

Returns

AsyncFunction — A single middleware function that runs all provided middleware in sequence.

Throws

  • TypeError — An element of the array is not a function.

Examples

import Koa from 'koa';
import compose from 'koa-compose';

const app = new Koa();

const authStack = compose([
  async (ctx, next) => {
    const token = ctx.get('Authorization');
    if (!token) ctx.throw(401);
    await next();
  },
  async (ctx, next) => {
    ctx.state.user = { id: 1 }; // decoded from token
    await next();
  },
]);

app.use(authStack);

app.use(async (ctx) => {
  ctx.body = { user: ctx.state.user };
});

app.listen(3000);
Output
GET / (no token)   → 401
GET / (with token) → {"user":{"id":1}}

Notes

`koa-compose` is the engine that powers Koa's own middleware stack internally. It implements the "onion model": each middleware wraps the next, and code after `await next()` runs after all downstream middleware has completed. Useful for building reusable middleware bundles (e.g. a single `apiStack` export that combines auth, logging, and rate limiting).

See also