✅ 405 Method Not Allowed - Automatic method validation
✅ 501 Not Implemented - Proper HTTP status codes
✅ Async/Await - Full promise-based middleware support
✅ Clean ctx.params - Only URL parameters you define are present in ctx.params; no internal routing keys leak out
Installation
npm:
npm install @koa/router
yarn:
yarn add @koa/router
Requirements:
Node.js >= 20 (tested on v20, v22, v24, v25)
Koa >= 2.0.0
TypeScript Support
@koa/router is written in TypeScript and includes comprehensive type definitions out of the box. No need for @types/* packages!
Basic Usage
Types are automatically inferred - no explicit type annotations needed:
import Router from '@koa/router';const router = new Router();// ctx and next are automatically inferred!router.get('/:id', (ctx, next) => { const id = ctx.params.id; // ✅ Inferred as string ctx.request.params.id; // ✅ Also available ctx.body = { id }; // ✅ Works return next(); // ✅ Works});// Also works for router.use()router.use((ctx, next) => { ctx.state.startTime = Date.now(); return next();});
Explicit Types (Optional)
For cases where you need explicit types:
import Router, { RouterContext } from '@koa/router';import type { Next } from 'koa';router.get('/:id', (ctx: RouterContext, next: Next) => { const id = ctx.params.id; ctx.body = { id };});
Generic Types
The router supports generic type parameters for full type safety with custom state and context types:
import Router, { RouterContext } from '@koa/router';import type { Next } from 'koa';// Define your application stateinterface AppState { user?: { id: string; email: string; };}// Define your custom contextinterface AppContext { requestId: string;}// Create router with genericsconst router = new Router<AppState, AppContext>();// Type-safe route handlersrouter.get( '/profile', (ctx: RouterContext<AppState, AppContext>, next: Next) => { // ctx.state.user is fully typed if (ctx.state.user) { ctx.body = { user: ctx.state.user, requestId: ctx.requestId // Custom context property }; } });
Extending Types in Route Handlers
HTTP methods support generic type parameters to extend state and context types:
import type { RouterParameterMiddleware } from '@koa/router';import type { Next } from 'koa';// Type-safe parameter middlewarerouter.param('id', ((value: string, ctx: RouterContext, next: Next) => { if (!/^\d+$/.test(value)) { ctx.throw(400, 'Invalid ID format'); } return next();}) as RouterParameterMiddleware);
Available Types
import { Router, RouterContext, RouterOptions, RouterMiddleware, RouterParameterMiddleware, AllowedMethodsOptions, UrlOptions, HttpMethod, MatchResult, LayerOptions, Layer, RouterEvent, RouterEventSelector, RouterEvents} from '@koa/router';import type { Next } from 'koa';// Router with genericstype MyRouter = Router<AppState, AppContext>;// Context with genericstype MyContext = RouterContext<AppState, AppContext, BodyType>;// Middleware with genericstype MyMiddleware = RouterMiddleware<AppState, AppContext, BodyType>;// Parameter middleware with genericstype MyParamMiddleware = RouterParameterMiddleware< AppState, AppContext, BodyType>;
Type Safety Features
✅ Full type inference - ctx and next are inferred automatically in route handlers
✅ Full generic support - Router<StateT, ContextT> for custom state and context types
✅ Type-safe parameters - ctx.params is fully typed and always defined
✅ Type-safe state - ctx.state respects your state type
✅ Type-safe middleware - Middleware functions are fully typed
✅ Type-safe HTTP methods - Methods support generic type extensions
✅ Custom HTTP method inference - Use as const with methods option for typed custom methods
✅ Compatible with @types/koa-router - Matches official type structure
Quick Start
import Koa from 'koa';import Router from '@koa/router';const app = new Koa();const router = new Router();// Define routesrouter.get('/', (ctx, next) => { ctx.body = 'Hello World!';});router.get('/users/:id', (ctx, next) => { ctx.body = { id: ctx.params.id };});// Apply router middlewareapp.use(router.routes()).use(router.allowedMethods());app.listen(3000);
API Documentation
Router Constructor
new Router([options])
Create a new router instance.
Options:
Option
Type
Description
prefix
string
Prefix all routes with this path
exclusive
boolean | 'specificity'
true: only run the last-registered matching route. 'specificity': only run the route with the fewest path parameters (OpenAPI-compliant). Omit to run all matching routes.
router.all(path, ...middleware) - Match any HTTP method
Note: All standard HTTP methods (as defined by Node.js http.METHODS) are automatically available as router methods. The methods option in the constructor can be used to limit which methods the router responds to, but you cannot use truly custom HTTP methods beyond the standard set.
Basic Example:
router .get('/users', getUsers) .post('/users', createUser) .put('/users/:id', updateUser) .delete('/users/:id', deleteUser) .all('/users/:id', logAccess); // Runs for any method
Using Less Common HTTP Methods:
All standard HTTP methods from Node.js are automatically available. Here's an example using PATCH and PURGE:
const router = new Router();// PATCH method (standard HTTP method for partial updates)router.patch('/users/:id', async (ctx) => { // Partial update ctx.body = { message: 'User partially updated' };});// PURGE method (standard HTTP method, commonly used for cache invalidation)router.purge('/cache/:key', async (ctx) => { // Clear cache await clearCache(ctx.params.key); ctx.body = { message: 'Cache cleared' };});// COPY method (standard HTTP method)router.copy('/files/:source', async (ctx) => { await copyFile(ctx.params.source, ctx.request.body.destination); ctx.body = { message: 'File copied' };});// Limiting which methods the router responds toconst apiRouter = new Router({ methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] // Only these methods});apiRouter.get('/users', getUsers);apiRouter.post('/users', createUser);// router.purge() won't work here because PURGE is not in the methods array
Note: HEAD requests are automatically supported for all GET routes. When you define a GET route, HEAD requests will execute the same handler and return the same headers but with an empty body.
const usersRouter = new Router();usersRouter.get('/', getUsers);usersRouter.get('/:id', getUser);const postsRouter = new Router();postsRouter.get('/', getPosts);postsRouter.get('/:id', getPost);const apiRouter = new Router({ prefix: '/api' });apiRouter.use('/users', usersRouter.routes());apiRouter.use('/posts', postsRouter.routes());app.use(apiRouter.routes());
Note: Parameters from parent routes are properly propagated to nested router middleware and handlers.
Router Prefixes
Set a prefix for all routes in a router:
Option 1: In constructor
const router = new Router({ prefix: '/api' });router.get('/users', handler); // Responds to /api/users
Option 2: Using .prefix()
const router = new Router();router.prefix('/api');router.get('/users', handler); // Responds to /api/users
With parameters:
const router = new Router({ prefix: '/api/v:version' });router.get('/users', (ctx) => { ctx.body = { version: ctx.params.version, users: [] };});// Responds to /api/v1/users, /api/v2/users, etc.
Middleware on a parameterized prefix:
When router.use() is attached to a router whose prefix contains URL parameters, ctx.params inside the middleware will contain only the parameters defined by the prefix — no internal routing keys are ever added.
const router = new Router({ prefix: '/:tenantId' });// Auth / authz middleware — receives only the defined prefix paramrouter.use(async (ctx, next) => { console.log(ctx.params); // => { tenantId: 'acme' } (no extraneous keys) await next();});router.get('/users', (ctx) => { console.log(ctx.params); // => { tenantId: 'acme' } ctx.body = ctx.params;});
This is particularly useful when running strict parameter validation inside a router.use() middleware — the shape of ctx.params is predictable and contains only what you defined.
URL Parameters
Named parameters are captured and available at ctx.params:
Note: Custom regex patterns in parameters (:param(regex)) are no longer supported in v14+ due to path-to-regexp v8. Use validation in handlers or middleware instead.
Helper for parameter validation (v14+) (Added on v15.2)
If you want to keep regex-style validation, register a param middleware instead:
Returns router middleware which dispatches matched routes.
app.use(router.routes());
router.use()
Use middleware, if and only if, a route is matched.
Signature:
router.use([path], ...middleware);
Examples:
// Run for all matched routesrouter.use(session());// Run only for specific pathrouter.use('/admin', requireAuth());// Run for multiple pathsrouter.use(['/admin', '/dashboard'], requireAuth());// Run for RegExp pathsrouter.use(/^\/api\//, apiAuth());// Mount nested routersconst nestedRouter = new Router();router.use('/nested', nestedRouter.routes());
Note: Middleware path boundaries are correctly enforced. Middleware scoped to /api will only run for routes matching /api/*, not for unrelated routes.
Note: When router.use() is used on a router with a parameterized prefix (e.g. prefix: '/:id'), ctx.params inside that middleware will contain only the parameters defined by the prefix and route path — no internal wildcard keys are exposed. See Router Prefixes for a full example.
router.prefix()
Set the path prefix for a Router instance after initialization.
const router = new Router();router.get('/', handler); // Responds to /router.prefix('/api');router.get('/', handler); // Now responds to /api
router.allowedMethods()
Returns middleware for responding to OPTIONS requests with allowed methods,
and 405 Method Not Allowed / 501 Not Implemented responses.
import type { RouterParameterMiddleware } from '@koa/router';import type { Next } from 'koa';router.param('user', (async (id: string, ctx: RouterContext, next: Next) => { ctx.state.user = await User.findById(id); if (!ctx.state.user) { ctx.throw(404, 'User not found'); } return next();}) as RouterParameterMiddleware);router.get('/users/:user', (ctx: RouterContext) => { // ctx.state.user is already loaded and typed ctx.body = ctx.state.user;});router.get('/users/:user/friends', (ctx: RouterContext) => { // ctx.state.user is available here too return ctx.state.user.getFriends();});
JavaScript Example:
router .param('user', async (id, ctx, next) => { ctx.state.user = await User.findById(id); if (!ctx.state.user) { ctx.throw(404, 'User not found'); } return next(); }) .get('/users/:user', (ctx) => { // ctx.state.user is already loaded ctx.body = ctx.state.user; }) .get('/users/:user/friends', (ctx) => { // ctx.state.user is available here too return ctx.state.user.getFriends(); });
Multiple param handlers:
You can register multiple param handlers for the same parameter. All handlers will be called in order, and each handler is executed exactly once per request (even if multiple routes match):
router .param('id', validateIdFormat) .param('id', checkIdExists) .param('id', checkPermissions) .get('/resource/:id', handler);// All three param handlers run once per request
Router.url() (static)
Generate URL from path pattern and parameters (static method).
Event name string, RouterEvents constant, or selector function
handler
RouterMiddleware
Middleware function (ctx, next) => {}
Returns: Router instance for chaining.
Active events:
Event
Constant
Description
'not-found'
RouterEvents.NotFound
Fires when no route matched path + method
Example:
import { RouterEvents } from '@koa/router';// All three forms are equivalent:router.on(RouterEvents.NotFound, handler); // constant (recommended)router.on((events) => events.NotFound, handler); // selector functionrouter.on('not-found', handler); // raw string// Handlers can be chained:router .on(RouterEvents.NotFound, async (ctx, next) => { console.log('no route matched:', ctx.path); await next(); }) .on(RouterEvents.NotFound, (ctx) => { ctx.status = 404; ctx.body = { error: 'Not Found' }; });
Note: This API is experimental and may change in future versions. See the
Not Found Event section in Advanced Features for details.
Advanced Features
Host Matching
Match routes only for specific hostnames:
// Exact match with single hostconst routerA = new Router({ host: 'example.com'});// Match multiple hosts with arrayconst routerB = new Router({ host: ['some-domain.com', 'www.some-domain.com', 'some.other-domain.com']});// Match patterns with RegExpconst routerC = new Router({ host: /^(.*\.)?example\.com$/ // Match all subdomains});
Host Matching Options:
string - Exact match (case-sensitive)
string[] - Matches if the request host equals any string in the array
RegExp - Pattern match using regular expression
undefined - Matches all hosts (default)
Regular Expressions
Use RegExp for flexible path matching:
Full RegExp routes:
router.get(/^\/users\/(\d+)$/, (ctx) => { const id = ctx.params[0]; // First capture group ctx.body = { id };});
router.param('id', (value, ctx, next) => { if (!/^\d+$/.test(value)) { ctx.throw(400, 'Invalid ID'); } ctx.params.id = parseInt(value, 10); // Convert to number return next();});router.get('/user/:id', handler);router.get('/post/:id', handler);// Both routes validate :id parameter
Catch-All Routes
Create a catch-all route that runs when no specific route handler has set a response.
Check !ctx.body to determine whether a previous handler already responded:
Note:ctx.matched.length === 0 will never be true inside a catch-all handler.
The router populates ctx.matchedbefore the handler body runs, so the catch-all
layer ({/*rest}) is already included in the array by the time your code executes.
Recommended: Use !ctx.body as shown above — it is the simplest and most reliable
condition inside a catch-all route.
Workaround: If you specifically need ctx.matched-based logic inside a catch-all,
filter out the catch-all layer first and check the remaining array:
For cleaner and more precise 404 detection, prefer app-level middleware with
ctx.routeMatched — see the 404 Handling section.
Array of Paths
Register multiple paths with the same middleware:
router.get(['/users', '/people'], handler);// Responds to both /users and /people
404 Handling
Implement custom 404 handling using app-level middleware after the router.
Using ctx.routeMatched (recommended):
app.use(router.routes());// ctx.routeMatched is set by the router before handlers runapp.use((ctx) => { if (!ctx.routeMatched) { ctx.status = 404; ctx.body = { error: 'Not Found', path: ctx.path }; }});
For a router-scoped alternative that doesn't require app-level middleware,
see the Not Found Event section below.
Not Found Event (Experimental)
Note: This API is experimental and may change in future versions.
Use router.on() for a clean, dedicated 404 handler that runs only when no route
matched — without needing a catch-all route. Three equivalent forms are supported:
import { RouterEvents } from '@koa/router';// Named constant (recommended — autocomplete + refactor safe)router.on(RouterEvents.NotFound, handler);// Selector function (fluent style)router.on((events) => events.NotFound, handler);// Raw string (still accepted)router.on('not-found', handler);
// ✅ Good: Group related routesconst usersRouter = new Router({ prefix: '/users' });usersRouter.get('/', listUsers);usersRouter.post('/', createUser);usersRouter.get('/:id', getUser);usersRouter.put('/:id', updateUser);usersRouter.delete('/:id', deleteUser);app.use(usersRouter.routes());
3. Use Named Routes
// ✅ Good: Name important routesrouter.get('home', '/', homeHandler);router.get('user-profile', '/users/:id', profileHandler);// Easy to generate URLsctx.redirect(ctx.router.url('home'));ctx.redirect(ctx.router.url('user-profile', ctx.state.user.id));
4. Validate Early
// ✅ Good: Validate at the route levelrouter .param('id', validateId) .get('/users/:id', getUser) .put('/users/:id', updateUser) .delete('/users/:id', deleteUser);// Validation runs once for all routes
API Versioning - Implement API versioning with multiple routers
Error Handling - Centralized error handling with custom error classes
Pagination - Implement pagination for list endpoints
Health Checks - Add health check endpoints for monitoring
TypeScript Recipe - Full TypeScript example with types and type safety
Not Found Handling - All approaches to handling unmatched routes: ctx.routeMatched, events, catch-all
Each recipe file contains complete, runnable TypeScript code that you can copy and adapt to your needs.
Performance
@koa/router is designed for high performance:
Fast path matching with path-to-regexp v8
Efficient RegExp compilation and caching
Minimal overhead - zero runtime type checking
Optimized middleware execution with koa-compose
Benchmarks:
# Run benchmarksyarn benchmark# Run all benchmark scenariosyarn benchmark:all
Testing
@koa/router uses Node.js native test runner:
# Run all tests (core + recipes)yarn test:all# Run core tests onlyyarn test:core# Run recipe tests onlyyarn test:recipes# Run tests with coverageyarn test:coverage# Type checkyarn ts:check# Format code with Prettieryarn format# Check code formattingyarn format:check# Lint codeyarn lint
Example test:
import { describe, it } from 'node:test';import assert from 'node:assert';import Koa from 'koa';import Router from '@koa/router';import request from 'supertest';describe('Router', () => { it('should route GET requests', async () => { const app = new Koa(); const router = new Router(); router.get('/users', (ctx) => { ctx.body = { users: [] }; }); app.use(router.routes()); const res = await request(app.callback()).get('/users').expect(200); assert.deepStrictEqual(res.body, { users: [] }); });});
Custom regex patterns in parameters (:param(regex)) are no longer supported due to path-to-regexp v8. Use validation in handlers or middleware instead.
Node.js >= 20 is required.
TypeScript types are now included in the package (no need for @types/@koa/router).
Upgrading:
Update Node.js to >= 20
Replace custom regex parameters with validation middleware
Remove @types/@koa/router if installed (types are now included)
Update any code using deprecated features
Backward Compatibility:
The code is mostly backward compatible. If you notice any issues when upgrading, please don't hesitate to open an issue and let us know!
Contributing
Contributions are welcome!
Development Setup
# Clone repositorygit clone https://github.com/koajs/router.gitcd router# Install dependencies (using yarn)yarn install# Run testsyarn test:all# Run tests with coverageyarn test:coverage# Format codeyarn format# Check formattingyarn format:check# Lint codeyarn lint# Build TypeScriptyarn build# Type checkyarn ts:check