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
koaand usually@koa/routerinpackage.json- Middleware shaped
async (ctx, next) => { ... await next() ... } - Responses set by assigning
ctx.bodyandctx.status
Where things usually live
- src/app.ts
- Creates the app and registers middleware in order.
- src/routes/
- Routers whose
routes()andallowedMethods()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
- The app file's
app.usecalls, top to bottom - The error-handling middleware, usually registered first
- The router for the path
How a request moves through the code
- The request enters the first middleware, typically error handling wrapped around everything else.
- Each middleware runs its code before
await next(), going inward. - The router matches and runs the handler, which sets
ctx.body. - Control 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
awaitbeforenext()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.