or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-koa-route

Uber simple route middleware for Koa.js applications with path parameter support

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/koa-route@4.0.x

To install, run

npx @tessl/cli install tessl/npm-koa-route@4.0.0

index.mddocs/

Koa Route

Koa Route is an uber simple route middleware for Koa.js applications. It provides minimalist routing functionality with path parameter support and pattern matching, focusing on simplicity and performance without the overhead of complex routing features.

Package Information

  • Package Name: koa-route
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install koa-route

Core Imports

const route = require('koa-route');

For ES6 modules:

import * as route from 'koa-route';

Basic Usage

const Koa = require('koa');
const route = require('koa-route');
const app = new Koa();

// Simple route with no parameters
app.use(route.get('/users', (ctx) => {
  ctx.body = 'All users';
}));

// Route with path parameter
app.use(route.get('/users/:id', (ctx, id) => {
  ctx.body = `User ${id}`;
}));

// Route supporting all HTTP methods
app.use(route.all('/api/:resource', (ctx, resource) => {
  ctx.body = `${ctx.method} request for ${resource}`;
}));

app.listen(3000);

Architecture

Koa Route provides a lightweight routing system built around:

  • Method-specific Route Creators: Individual functions for each HTTP method (get, post, put, etc.)
  • Universal Route Creator: all() method that matches any HTTP method
  • Path Pattern Matching: Powered by path-to-regexp for parameter extraction and pattern matching
  • Middleware Generation: Each route function returns standard Koa middleware
  • Context Enhancement: Adds routePath property to Koa context for matched routes

Capabilities

HTTP Method Routing

Route creators for all standard HTTP methods, each generating middleware that matches specific HTTP methods and URL patterns.

/**
 * Create route middleware for GET requests
 * @param {string} path - URL pattern with optional parameters (uses path-to-regexp syntax)
 * @param {Function} [handler] - Route handler function with signature (ctx, ...params, next)
 * @param {Object} [options] - Options passed to path-to-regexp
 * @returns {Function} Koa middleware function or route creator function
 */
function get(path, handler, options);

/**
 * Create route middleware for POST requests
 * @param {string} path - URL pattern with optional parameters
 * @param {Function} [handler] - Route handler function
 * @param {Object} [options] - Options for path-to-regexp
 * @returns {Function} Koa middleware function or route creator function
 */
function post(path, handler, options);

/**
 * Create route middleware for PUT requests
 * @param {string} path - URL pattern with optional parameters
 * @param {Function} [handler] - Route handler function
 * @param {Object} [options] - Options for path-to-regexp
 * @returns {Function} Koa middleware function or route creator function
 */
function put(path, handler, options);

/**
 * Create route middleware for PATCH requests
 * @param {string} path - URL pattern with optional parameters
 * @param {Function} [handler] - Route handler function
 * @param {Object} [options] - Options for path-to-regexp
 * @returns {Function} Koa middleware function or route creator function
 */
function patch(path, handler, options);

/**
 * Create route middleware for DELETE requests
 * @param {string} path - URL pattern with optional parameters
 * @param {Function} [handler] - Route handler function
 * @param {Object} [options] - Options for path-to-regexp
 * @returns {Function} Koa middleware function or route creator function
 */
function delete(path, handler, options);

/**
 * Alias for delete method (since 'delete' is a reserved keyword)
 * Same function as delete(), provided for convenience
 */
const del = delete;

/**
 * Create route middleware for HEAD requests
 * @param {string} path - URL pattern with optional parameters
 * @param {Function} [handler] - Route handler function
 * @param {Object} [options] - Options for path-to-regexp
 * @returns {Function} Koa middleware function or route creator function
 */
function head(path, handler, options);

/**
 * Create route middleware for OPTIONS requests
 * @param {string} path - URL pattern with optional parameters
 * @param {Function} [handler] - Route handler function
 * @param {Object} [options] - Options for path-to-regexp
 * @returns {Function} Koa middleware function or route creator function
 */
function options(path, handler, options);

// All HTTP methods from the 'methods' npm package are dynamically exported.
// Complete list of available methods:
function acl(path, handler, options);
function bind(path, handler, options);
function checkout(path, handler, options);
function connect(path, handler, options);
function copy(path, handler, options);
function link(path, handler, options);
function lock(path, handler, options);
function merge(path, handler, options);
function mkactivity(path, handler, options);
function mkcalendar(path, handler, options);
function mkcol(path, handler, options);
function move(path, handler, options);
function notify(path, handler, options);
function propfind(path, handler, options);
function proppatch(path, handler, options);
function purge(path, handler, options);
function rebind(path, handler, options);
function report(path, handler, options);
function search(path, handler, options);
function source(path, handler, options);
function subscribe(path, handler, options);
function trace(path, handler, options);
function unbind(path, handler, options);
function unlink(path, handler, options);
function unlock(path, handler, options);
function unsubscribe(path, handler, options);

Usage Examples:

const route = require('koa-route');

// Direct handler assignment
app.use(route.get('/posts', (ctx) => {
  ctx.body = 'All posts';
}));

// Route with parameters
app.use(route.post('/posts/:id', (ctx, id) => {
  ctx.body = `Created post ${id}`;
}));

// Complex parameter patterns
app.use(route.get('/users/:id(\\\\d+)', (ctx, id) => {
  ctx.body = `User with numeric ID: ${id}`;
}));

// Optional parameters
app.use(route.get('/api/:resource/:id?', (ctx, resource, id) => {
  if (id) {
    ctx.body = `${resource} item ${id}`;
  } else {
    ctx.body = `All ${resource}`;
  }
}));

Universal Method Routing

Route creator that matches all HTTP methods for a given path pattern.

/**
 * Create route middleware that matches all HTTP methods
 * @param {string} path - URL pattern with optional parameters (uses path-to-regexp syntax)
 * @param {Function} [handler] - Route handler function with signature (ctx, ...params, next)
 * @param {Object} [options] - Options passed to path-to-regexp
 * @returns {Function} Koa middleware function or route creator function
 */
function all(path, handler, options);

Usage Examples:

// Match all methods for API endpoint
app.use(route.all('/api/:resource', (ctx, resource) => {
  ctx.body = `${ctx.method} request for ${resource}`;
}));

// Composed route creation
const apiRoute = route.all('/api/:action');
app.use(apiRoute((ctx, action) => {
  ctx.body = `API action: ${action}`;
}));

Composed Route Creation

All route functions support composed creation where the handler is provided separately from the path pattern.

/**
 * Route creator function returned when handler is omitted
 * @param {Function} handler - Route handler function with signature (ctx, ...params, next)
 * @returns {Function} Koa middleware function
 */
function routeCreator(handler);

Usage Examples:

// Create reusable route patterns
const userRoute = route.get('/users/:id');
const postRoute = route.get('/posts/:id');

// Apply different handlers to same pattern
app.use(userRoute((ctx, id) => {
  ctx.body = `User ${id}`;
}));

app.use(postRoute((ctx, id) => {
  ctx.body = `Post ${id}`;
}));

Types

Route Handler Function

/**
 * Route handler function signature
 * @param {Object} ctx - Koa context object with added routePath property
 * @param {...string} routeParams - Decoded URL parameters extracted from route pattern  
 * @param {Function} next - Koa next function for middleware chaining
 * @returns {Promise|void} Promise that resolves when handler completes, or void for synchronous handlers
 */
function routeHandler(ctx, ...routeParams, next);

Enhanced Koa Context

When a route matches, koa-route enhances the Koa context with additional properties:

/**
 * Enhanced Koa context with route information
 */
interface EnhancedContext extends KoaContext {
  /** The original route pattern that matched the request */
  routePath: string;
}

Path-to-Regexp Options

Options object passed to the underlying path-to-regexp library for advanced pattern matching:

/**
 * Options for path-to-regexp pattern matching
 */
interface PathToRegexpOptions {
  /** When true, the regexp allows an optional trailing delimiter to match */
  strict?: boolean;
  /** When true, the regexp will not match trailing delimiter */
  end?: boolean;
  /** When true, the regexp will be case sensitive */
  sensitive?: boolean;
}

Advanced Usage

Method Matching Behavior

  • GET routes automatically handle HEAD requests: HEAD requests to GET routes return the same response with an empty body
  • All other methods require exact matching: POST, PUT, DELETE, etc. only match their specific method
  • Universal matching with all(): The all() method matches any HTTP method

Parameter Decoding

Route parameters are automatically URL-decoded using decodeURIComponent():

// URL: /package/http%3A%2F%2Fgithub.com
app.use(route.get('/package/:name', (ctx, name) => {
  // name === 'http://github.com' (automatically decoded)
  ctx.body = `Package: ${name}`;
}));

Path Pattern Features

Supports all path-to-regexp pattern features:

  • Static paths: /users
  • Named parameters: /users/:id
  • Optional parameters: /users/:id?
  • Custom regex patterns: /users/:id(\\\\d+)
  • Multiple parameters: /users/:userId/posts/:postId

Error Handling

When routes don't match:

  • The middleware calls next() to continue to the next middleware
  • No automatic error responses are generated
  • 404 handling should be implemented at the application level