Skip to content

About

koa route middleware

Resources

Code of conduct

Contributing

Security policy

Stars

37 stars

Watchers

3 watching

Forks

Latest commit

 

History

133 Commits

Folders and files

Repository files navigation

Koa Path Match

NPM version Node.js CI Test coverage License Downloads

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-regexp was 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
    })
)

Requirements

  • Node.js 24.0.0 or higher

Upgrading from v5

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

Maintainer

API

route(path, fns...)

paths are just like Express routes. fns is either a single middleware or nested arrays of middleware, just like Express.

const router = route(path)

When you don't set fns in the route() function, a router instance is returned.

router[method](fns...)

Define a middleware just for a specific method.

app.use(
  route('/:id').get(async (ctx) => {
    ctx.body = await Things.getById(ctx.params.id)
  })
)
  • next is not passed as a parameter. I consider this an anti-pattern in Koa - one route/method, one function.

this.params

Any keys defined in the path will be set to ctx.params, overwriting any already existing keys defined.

About

koa route middleware

Resources

Code of conduct

Contributing

Security policy

Stars

37 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages