koa-advanced-patterns
Installation
SKILL.md
Koa.js Professional Standards
Middleware Architecture
- The Async Promise Chain: ALWAYS declare middleware as
async (ctx, next) => { ... }. - Await Next: You MUST
await next()exactly once in every middleware. - Execution Order: Code before
await next()handles the Request; code after handles the Response.
Reliability & Ops
- Graceful Shutdown: Do not kill the server instantly. Listen for system signals (
SIGTERM,SIGINT).- Pattern: Stop accepting new requests -> Close database connections -> Exit process.
- Example:
server.close(() => db.disconnect()).
- Health Checks: Always implement a
/healthendpoint for load balancers (return 200 OK if DB is connected).
Context (ctx) Mastery
- State Management: Use
ctx.stateto pass data between middleware (e.g.,ctx.state.user). NEVER pollute the global namespace. - Request Data: Access via
ctx.request.body,ctx.query, orctx.params. - Response Construction: Explicitly set
ctx.statusbefore settingctx.body.
Related skills