koa-rewrite

raw JSON →
3.0.1 verified Sat Apr 25 auth: no javascript

URL rewrite middleware for Koa. Current version 3.0.1 supports Koa 2. Release cadence is stable but infrequent. Key differentiators: simple API using regex or route parameters similar to Express, debug support via DEBUG environment variable. Alternative libraries like koa-route provide routing only.

error Error: Cannot find module 'koa-rewrite'
cause Package not installed or wrong path.
fix
Run 'npm install koa-rewrite'.
error TypeError: rewrite is not a function
cause Incorrect import: the module exports a function but was imported as an object.
fix
Use 'import rewrite from 'koa-rewrite'' or 'const rewrite = require('koa-rewrite')'.
breaking koa-rewrite@2+ only supports koa@2; use koa-rewrite@1 for koa@1.
fix Install koa-rewrite@1 for koa@1, or upgrade to koa@2.
gotcha The rewrite does not change the HTTP method; only URL.
fix Use additional middleware to handle method modifications.
gotcha Regex pattern must match entire path from start; otherwise unexpected matches.
fix Anchor regex at start with ^, e.g., /^\/old(.*)/.
npm install koa-rewrite
yarn add koa-rewrite
pnpm add koa-rewrite

Basic Koa server with URL rewrite: /i123 becomes /items/123.

import Koa from 'koa';
import rewrite from 'koa-rewrite';

const app = new Koa();
app.use(rewrite(/^\/i(\w+)/, '/items/$1'));
app.use(ctx => {
  ctx.body = ctx.url;
});
app.listen(3000);