Koa Compose Middleware Pipeline Order

Compose Koa middleware functions in explicit execution order, tracing the onion model pass-through with early termination and downstream control.

JavascriptResilience

Code

javascriptsnippet
28 lines
import Koa from 'koa';
import compose from 'koa-compose';

async function timing(ctx, next) {
  const started = Date.now();
  await next();
  ctx.set('x-response-time', String(Date.now() - started));
}

async function guard(ctx, next) {
  if (ctx.path === '/internal') {
    ctx.status = 403;
    return; // early termination: downstream never runs
  }
  await next();
}

async function body(ctx) {
  ctx.body = { ok: true };
}

const app = new Koa();
app.use(compose([timing, guard, body]));

const pipeline = compose([timing, guard, body]);
const ctx = app.createContext(null, null);
await pipeline(ctx, () => Promise.resolve());
console.log('composed response headers:', ctx.response.status);

What the code does

Koa Compose Middleware Pipeline Order is built around the functions timing, guard and body.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

What to watch for

  • koa and koa-compose must be installed first — the snippet imports them directly.

Applying it

The main signature reads async function timing(ctx, next)

The run emits 1 labeled section — composed response headers: — one per step.

Statements that matter

await pipeline(ctx, () => Promise.resolve());
await next();

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
`koa` and `koa-compose` — install them with the package manager before running.