@koa/router
Express-style router for Koa that provides method-specific routing, URL parameters, and route-level middleware.
Syntax
import Router from '@koa/router';
const router = new Router([options]);
router.get(path, ...middleware);
app.use(router.routes()).use(router.allowedMethods());
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
options | object | No | Router options: `prefix` (string path prefix for all routes), `strict` (boolean, treat `/foo` and `/foo/` as different), `sensitive` (boolean, case-sensitive paths). |
Returns
Router — A Router instance with methods for each HTTP verb.
Examples
import Koa from 'koa';
import Router from '@koa/router';
const app = new Koa();
const router = new Router();
router.get('/users', async (ctx) => {
ctx.body = [{ id: 1, name: 'Alice' }];
});
router.get('/users/:id', async (ctx) => {
ctx.body = { id: ctx.params.id };
});
router.post('/users', async (ctx) => {
ctx.status = 201;
ctx.body = { created: true };
});
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);
Output
GET /users → [{"id":1,"name":"Alice"}]
GET /users/42 → {"id":"42"}
POST /users → 201 {"created":true}
// Nested router with prefix
const api = new Router({ prefix: '/api/v1' });
api.get('/health', async (ctx) => {
ctx.body = { status: 'ok' };
});
app.use(api.routes());
Output
GET /api/v1/health → {"status":"ok"}
Notes
`router.allowedMethods()` handles `OPTIONS` preflight requests and returns
`405 Method Not Allowed` with an `Allow` header for routes that exist
but don't support the used method. Use `router.param()` to add
middleware that runs whenever a particular URL parameter is matched.