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.
Common errors
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')'.
Warnings
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(.*)/.
Install
npm install koa-rewrite yarn add koa-rewrite pnpm add koa-rewrite Imports
- rewrite wrong
const rewrite = require('koa-rewrite')correctimport rewrite from 'koa-rewrite'
Quickstart
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);