Koa Route Middleware

4.0.1 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up basic GET routes for a simple pet API using `koa-route` with a Koa application, handling both listing all pets and showing a specific pet by name.

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

view raw JSON →