Koa Route Middleware
koa-route provides a minimalist routing solution for Koa applications. It offers a simple API to define HTTP method-specific routes (e.g., `.get`, `.post`) directly as middleware functions. Its current stable version is 4.0.1. Releases are infrequent, primarily tied to underlying dependency updates or minor API refinements, reflecting its stable and mature nature. It differentiates itself from more feature-rich alternatives like `koa-router` by explicitly prioritizing simplicity and minimal overhead. This makes it suitable for smaller applications or specific middleware-based routing needs where the full complexity of a dedicated routing framework is not required, as it does not offer advanced features such as nested routes, prefixing, or extensive middleware composition.
Common errors
-
Cannot GET /some-undefined-route
cause The requested URL path and HTTP method do not match any defined route using `koa-route` in your application.fixVerify that the URL path (`/some-undefined-route`) and the HTTP method (GET) precisely match a route defined with `_.get('/some-undefined-route', handler)`. Check for typos in the path or an incorrect HTTP method. -
TypeError: handler must be a function
cause `koa-route` expects a valid Koa middleware function as the second argument to its method helpers (e.g., `_.get()`, `_.post()`). This error occurs if a non-function value is passed.fixEnsure the argument passed to `_.get()`, `_.post()`, etc., is indeed a function. This often happens due to typos in function names, unimported handlers, or incorrect variable assignments. -
ReferenceError: _ is not defined
cause The `koa-route` module was not correctly imported or assigned to the `_` variable before being used in the application.fixFor CommonJS, add `const _ = require('koa-route');` at the top of your file. For ESM, use `import _ from 'koa-route';` or `import route from 'koa-route';` to import the module.
Warnings
- breaking Upgrading to `koa-route` v4.0.0 included an upgrade to `path-to-regexp@6`. This introduced subtle breaking changes in how routes are parsed, especially regarding advanced regex features, unnamed parameters, and trailing slashes, which may affect existing route definitions.
- breaking `koa-route` v3.0.0 introduced support for Koa 2.x's async/await middleware signature, making it incompatible with Koa 1.x. Koa 1 applications using `koa-route` must remain on versions prior to 3.0.0.
- gotcha In `koa-route` v4.0.0 specifically, route handlers were strictly enforced to be functions, throwing a `TypeError` if a non-function was provided. This strict validation was immediately reverted in v4.0.1, making v4.0.0 an unstable release in this regard.
- gotcha Many `koa-route` examples, including in its own documentation, suggest importing the module as `_`. While functional, this can lead to naming conflicts with other popular libraries that commonly use `_` (e.g., Lodash or Underscore.js), especially in larger codebases, potentially causing unexpected behavior or confusion.
Install
-
npm install koa-route -
yarn add koa-route -
pnpm add koa-route
Imports
- Default export object
import { get } from 'koa-route';import route from 'koa-route';
- CommonJS require
const { get } = require('koa-route');const _ = require('koa-route'); - Middleware and Context Types
import type { Middleware, Context } from 'koa'; import route from 'koa-route';
Quickstart
const _ = require('koa-route');
const Koa = require('koa');
const app = new Koa();
const db = {
tobi: { name: 'tobi', species: 'ferret' },
loki: { name: 'loki', species: 'ferret' },
jane: { name: 'jane', species: 'ferret' }
};
const pets = {
list: (ctx) => {
const names = Object.keys(db);
ctx.body = 'pets: ' + names.join(', ');
},
show: (ctx, name) => {
const pet = db[name];
if (!pet) return ctx.throw('cannot find that pet', 404);
ctx.body = pet.name + ' is a ' + pet.species;
}
};
app.use(_.get('/pets', pets.list));
app.use(_.get('/pets/:name', pets.show));
const PORT = process.env.PORT || 3000;
app.listen(PORT, (err) => {
if (err) console.error(err.stack);
else console.log(`Koa server listening on port ${PORT}`);
});