Koa Path Match
raw JSON →koa-path-match is a lightweight routing middleware designed for Koa.js applications, currently stable at version 5.0.0. It functions as a minimalist path matcher built on top of the `path-match` library, which itself uses `path-to-regexp` for robust URL pattern matching, mirroring the routing logic found in Express.js. This package distinguishes itself by offering fine-grained control over HTTP method handling and advocating for a single-function-per-route paradigm, intentionally omitting the `next` parameter in method-specific middleware to streamline logic. Its release cycle is closely tied to major version updates of its core `path-to-regexp` dependency. It serves as an efficient solution for basic route dispatching without the complexity of a full-featured routing framework, suitable for microservices or simple API endpoints.
Common errors
error ReferenceError: require is not defined ↓
type: "module" in package.json or .mjs files, change const route = require('koa-path-match')() to import routeFactory from 'koa-path-match'; const route = routeFactory(); error TypeError: (0 , koa_path_match_1.default) is not a function ↓
import routeFactory from 'koa-path-match'; const route = routeFactory(); instead of import route from 'koa-path-match'; error Error: 'koa-path-match' is not compatible with Node.js <18.0.0 ↓
nvm install 18 && nvm use 18) or downgrade koa-path-match to version 3.x if you cannot upgrade Node.js. Warnings
breaking Version 4.0.0 and above of `koa-path-match` dropped support for Node.js versions prior to 18. Attempting to use it on older Node.js environments will result in runtime errors. ↓
breaking Major versions of `koa-path-match` (v3, v4, v5) update their underlying `path-to-regexp` dependency. These updates can introduce subtle breaking changes in how path patterns are parsed, especially for complex regular expressions or new features. ↓
gotcha When a route matches, any keys defined in the path (e.g., `:id`) will be set on `ctx.params`, potentially overwriting existing keys if they share the same name. ↓
gotcha Middleware functions defined using method-specific chaining (e.g., `route().get(async ctx => { ... })`) are not passed the `next` function as a parameter. This is an intentional design choice to encourage single-function, single-responsibility handlers. ↓
Install
npm install koa-path-match yarn add koa-path-match pnpm add koa-path-match Imports
- route wrong
import { route } from 'koa-path-match'correctimport route from 'koa-path-match' - route wrong
const { route } = require('koa-path-match')correctconst route = require('koa-path-match')() - PathMatchOptions
import type { PathMatchOptions } from 'koa-path-match'
Quickstart
const Koa = require('koa');
const route = require('koa-path-match')(); // Initialize the router factory
const app = new Koa();
// Simulate a database/data store
const Things = {
data: {
'123': { id: '123', name: 'Thing One' },
'456': { id: '456', name: 'Thing Two' }
},
async getById(id) {
return this.data[id];
},
async delete(id) {
delete this.data[id];
}
};
app.use(route('/:id(\d+)')
.get(async ctx => {
const thing = await Things.getById(ctx.params.id);
if (thing) {
ctx.body = thing;
} else {
ctx.status = 404;
ctx.body = { message: 'Not Found' };
}
})
.delete(async ctx => {
await Things.delete(ctx.params.id);
ctx.status = 204;
})
);
// Generic 404 handler if no route matches
app.use(async ctx => {
if (ctx.status === 404 && !ctx.body) {
ctx.body = { message: 'Route not handled' };
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Koa app running on port http://localhost:${PORT}`);
console.log('Try: GET http://localhost:3000/123');
console.log('Try: DELETE http://localhost:3000/456');
});