A simple routing wrapper around Node.js 24's native URLPattern. Similar to koa-route, except it optionally handles methods better. This package uses the native URLPattern API which provides similar functionality to Express's routing.
NOTE: for older versions,
path-to-regexpwas used. In v5, regexp capture groups were removed, but are added back in v6 with the migration to URLPattern.
NOTE: koa-path-match@6 only supports node v24+. Please use an older version of koa-path-match for older versions of node.
const route = require('koa-path-match')({
/* options passed to URLPattern, e.g. { ignoreCase: true } */
})
app.use(
route('/:id', (ctx, next) => {
const id = ctx.params.id
// do stuff
switch (ctx.request.method) {
}
})
)Or you can create middleware per method:
app.use(
route('/:id')
.get(async (ctx) => {
ctx.body = await Things.getById(ctx.params.id)
})
.delete(async (ctx) => {
await Things.delete(ctx.params.id)
ctx.status = 204
})
)- Node.js 24.0.0 or higher
v6 matches paths with the native URLPattern instead of path-to-regexp@8, so some behavior changes:
v5 (path-to-regexp) |
v6 (URLPattern) |
|
|---|---|---|
| Param values | URL-decoded: /users/caf%C3%A9 gives id: 'café' |
Left as-is: id: 'caf%C3%A9'. Call decodeURIComponent() yourself if you need the decoded value |
| Case | Case-insensitive | Case-sensitive. Pass { ignoreCase: true } to restore v5 matching |
| Options | Passed to path-to-regexp |
Passed to URLPattern (ignoreCase) |
| Wildcard | /files/*rest gives rest: ['a', 'b'] |
/files/:rest+ gives rest: 'a/b', or /files/* gives 0: 'a/b' |
| Optional segment | /a{/:b} |
/a{/:b}? or /a/:b? |
| Regexp params | Not supported | /:id(\d+) |
route(path).match |
path-to-regexp match function |
Removed. route(path).pattern is the URLPattern |
- Lead: @jonathanong @jongleberry
- Team: @koajs/routing
paths are just like Express routes. fns is either a single middleware
or nested arrays of middleware, just like Express.
When you don't set fns in the route() function, a router instance is returned.
Define a middleware just for a specific method.
app.use(
route('/:id').get(async (ctx) => {
ctx.body = await Things.getById(ctx.params.id)
})
)nextis not passed as a parameter. I consider this an anti-pattern in Koa - one route/method, one function.
Any keys defined in the path will be set to ctx.params,
overwriting any already existing keys defined.