Koa Path Match

raw JSON →
5.0.0 verified Thu Apr 23 auth: no javascript

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.

error ReferenceError: require is not defined
cause Attempting to use `require()` in an ECMAScript Module (ESM) context without proper configuration.
fix
If your project uses 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
cause Incorrectly importing the default export in ESM when the factory function itself needs to be called immediately.
fix
Ensure you are calling the imported default export: 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
cause Running `koa-path-match` v4 or higher on an unsupported Node.js version.
fix
Update your Node.js environment to version 18 or newer (e.g., using nvm install 18 && nvm use 18) or downgrade koa-path-match to version 3.x if you cannot upgrade Node.js.
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.
fix Upgrade your Node.js environment to version 18 or higher, or pin `koa-path-match` to version 3.x for older Node.js environments.
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.
fix Review the changelogs for `path-to-regexp` when upgrading major versions. Thoroughly test existing routes, particularly those with advanced regex patterns or custom options, after an upgrade.
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.
fix Be aware of potential key collisions in `ctx.params`. If you need to preserve existing keys, manually merge or rename them before `koa-path-match` sets its parameters, or use unique parameter names in your routes.
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.
fix If you require middleware chaining or explicit `next()` calls, define your middleware using the `app.use(route(path, fns...))` syntax with an array of middleware, or structure your application such that each route handler is self-contained.
npm install koa-path-match
yarn add koa-path-match
pnpm add koa-path-match

Demonstrates how to set up a basic Koa application using `koa-path-match` for method-specific routing and parameter extraction.

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');
});