Koa URL Rewrite Middleware

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

koa-rewrite is a specialized URL rewriting middleware designed for the Koa.js web framework. It enables developers to dynamically modify incoming request URLs based on defined patterns before they are processed by subsequent middleware or routing logic. The current stable version, 3.0.1, is compatible with Koa v2 and newer, while `koa-rewrite@1` is designated for Koa v1 applications. The library offers flexible rewrite rule definition through regular expressions, named and numeric route parameters, and wildcard matching. It provides a focused, lightweight solution for common URL manipulation needs within the Koa ecosystem, prioritizing simplicity and efficiency for path transformations rather than comprehensive routing. Releases are infrequent, primarily aligning with significant Koa framework updates.

error TypeError: app.use is not a function
cause Attempting to use `koa-rewrite@2+` with an application initialized with Koa v1, which has different API patterns for `app.use`.
fix
Upgrade Koa to version 2 or higher (e.g., npm install koa@latest) or downgrade koa-rewrite to version 1 (e.g., npm install koa-rewrite@1).
error 404 Not Found (when a rewrite rule should apply)
cause The `koa-rewrite` middleware is placed too late in the Koa middleware chain, after a router or other middleware has already attempted to match the original URL and failed, or the original URL was consumed.
fix
Ensure koa-rewrite middleware is registered early in your application's middleware stack, typically before any routing middleware (@koa/router) or static file serving middleware.
breaking Version `koa-rewrite@2.0.0` and above are exclusively compatible with Koa v2.x and newer. Applications using Koa v1.x must use `koa-rewrite@1.x`.
fix Ensure your `koa-rewrite` version matches your Koa framework version. Upgrade Koa to v2+ or use `npm install koa-rewrite@1` if on Koa v1.
gotcha Debugging output for `koa-rewrite` is controlled via the `DEBUG` environment variable. Enable it with `DEBUG=koa-rewrite`.
fix Set the `DEBUG` environment variable (e.g., `DEBUG=koa-rewrite node app.js`) to see rewrite logs.
gotcha The order of middleware is crucial. `koa-rewrite` should be placed before any routing middleware (like `@koa/router`) or static file servers to ensure URL rewriting occurs before path matching.
fix Register `app.use(rewrite(...))` statements before `app.use(router.routes())` or static middleware.
npm install koa-rewrite-75lb
yarn add koa-rewrite-75lb
pnpm add koa-rewrite-75lb

This example sets up a basic Koa application with `koa-rewrite` to demonstrate regex, parameter-based, and wildcard URL rewriting. It uses `@koa/router` to handle the rewritten paths. To run, install `koa`, `koa-rewrite`, and `@koa/router`.

import Koa from 'koa';
import rewrite from 'koa-rewrite';
import Router from '@koa/router';

const app = new Koa();
const router = new Router();

// Middleware order matters: rewrite before router
app.use(rewrite(/^\/i(\d+)/, '/items/$1'));
app.use(rewrite('/:src..:dst', '/commits/:src/to/:dst'));
app.use(rewrite('/js/(.*)', '/public/assets/js/$1')); // Example: /js/main.js -> /public/assets/js/main.js

router.get('/items/:id', (ctx) => {
  ctx.body = `Item ID: ${ctx.params.id}`;
});

router.get('/commits/:src/to/:dst', (ctx) => {
  ctx.body = `Commits from ${ctx.params.src} to ${ctx.params.dst}`;
});

router.get('/public/assets/js/:path*', (ctx) => {
  ctx.body = `Serving static JS file: /public/assets/js/${ctx.params.path}`;
});

router.get('/', (ctx) => {
  ctx.body = 'Hello, Koa Rewrite!';
});

app.use(router.routes()).use(router.allowedMethods());

const PORT = process.env.PORT ?? 3000;
app.listen(PORT, () => {
  console.log(`Koa server running on http://localhost:${PORT}`);
  console.log('Try:');
  console.log(`- http://localhost:${PORT}/i123 (should rewrite to /items/123)`);
  console.log(`- http://localhost:${PORT}/foo..bar (should rewrite to /commits/foo/to/bar)`);
  console.log(`- http://localhost:${PORT}/js/vendor/library.js (should rewrite to /public/assets/js/vendor/library.js)`);
});