Koa Context and State
Question Variations
- "Why use `ctx.state` rather than a module global for the authenticated user?"
- "When should you avoid writing to `ctx.res` directly?"
- "How can TypeScript type custom Koa state?"
Why This Is Asked
Koa combines HTTP request and response operations in a per-request context object. This question tests whether you pass request-scoped data safely without relying on global mutable state.
Key Concepts
ctxis created per request and provides request and response helpers.ctx.stateis the recommended namespace for data shared by middleware and handlers.ctx.reqandctx.resare raw Node objects and usually should not be written directly.- Application-wide dependencies should not be mutable request state.
Question Variations
- “Why use
ctx.staterather than a module global for the authenticated user?” - “When should you avoid writing to
ctx.resdirectly?” - “How can TypeScript type custom Koa state?”