Koa Web Framework
Koa is an expressive HTTP middleware framework for Node.js, designed to build web applications and APIs. It emphasizes a small core, relying on its middleware stack for functionality, and does not bundle any middleware. The current stable version is 3.2.0, with active development across both v2 and v3 branches, indicating a continuous release cadence.
Common errors
-
SyntaxError: await is only valid in async functions and the top level bodies of modules
cause Attempting to use `await` within a Koa middleware function that is not declared as `async`.fixDeclare your middleware function as `async`, e.g., `app.use(async (ctx, next) => { await next(); });`. -
Error: next() cannot be called more than once
cause A Koa middleware function is invoking `next()` multiple times, or not awaiting it correctly, leading to re-entrancy issues.fixEnsure `await next();` is called exactly once within each middleware. Review error handling logic or early exits that might bypass `await next()`. -
TypeError: ctx.render is not a function
cause Attempting to use a feature like template rendering (e.g., `ctx.render`) without installing and registering the corresponding Koa middleware.fixInstall the necessary Koa-compatible middleware package (e.g., `koa-views` for template rendering) and register it with `app.use()`. -
ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client
cause Attempting to modify HTTP headers or send response content after the response has already been partially or fully sent to the client.fixEnsure that `ctx.set()` or `ctx.body = ...` operations occur before any part of the response has been flushed. This often happens if `await next()` is omitted or if asynchronous operations continue after the response is sent.
Warnings
- breaking Koa v3 removed support for the deprecated v1.x middleware signature. Middleware functions must now be `async` functions or return `Promise`s.
- gotcha Koa provides a minimal core and does not bundle any middleware. Essential functionalities like routing, body parsing, or sessions must be added via separate middleware packages.
- breaking Koa requires Node.js v18.0.0 or higher due to its reliance on ES2015 features and async/await support.
- gotcha Versions of Koa prior to v2.16.4 and specific earlier v3.x releases contained a Host Header Injection vulnerability via `ctx.hostname` (GHSA-7gcc-r8m5-44qm).
Install
-
npm install koa -
yarn add koa -
pnpm add koa
Imports
- Koa
const Koa = require('koa');import Koa from 'koa';
Quickstart
import Koa from 'koa';
const app = new Koa();
// response
app.use(ctx => {
ctx.body = 'Hello Koa';
});
app.listen(3000, () => {
console.log('Koa server listening on port 3000');
});