Skip to content

How to understand a Koa codebase

Koa is a small framework built on async middleware that forms an onion: each middleware runs code before `await next()`, lets the rest of the stack run, then runs code after. Request and response live together on `ctx`.

How to tell it's Koa

  • koa and usually @koa/router in package.json
  • Middleware shaped async (ctx, next) => { ... await next() ... }
  • Responses set by assigning ctx.body and ctx.status

Where things usually live

src/app.ts
Creates the app and registers middleware in order.
src/routes/
Routers whose routes() and allowedMethods() are mounted on the app.
src/middleware/
Auth, errors, logging, body parsing.
src/services/
Business logic.

Conventions, not rules. Real projects rename and move things, so confirm against the repository.

Where to start reading

  1. The app file's app.use calls, top to bottom
  2. The error-handling middleware, usually registered first
  3. The router for the path

How a request moves through the code

  1. 1The request enters the first middleware, typically error handling wrapped around everything else.
  2. 2Each middleware runs its code before await next(), going inward.
  3. 3The router matches and runs the handler, which sets ctx.body.
  4. 4Control returns outward through each middleware's code after await next(), such as timing and logging.

Questions to ask about the repository

  • In what order does middleware run, and what does each do after next() returns?
  • Where are errors caught and formatted?
  • What does this app put on ctx.state?

What trips people up

  • Forgetting await before next() breaks the onion; downstream errors escape the error handler.
  • If no middleware sets ctx.body, Koa returns 404 even though a route seemed to run.