Koa URL Rewrite Middleware
raw JSON →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.
Common errors
error TypeError: app.use is not a function ↓
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) ↓
koa-rewrite middleware is registered early in your application's middleware stack, typically before any routing middleware (@koa/router) or static file serving middleware. Warnings
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`. ↓
gotcha Debugging output for `koa-rewrite` is controlled via the `DEBUG` environment variable. Enable it with `DEBUG=koa-rewrite`. ↓
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. ↓
Install
npm install koa-rewrite-75lb yarn add koa-rewrite-75lb pnpm add koa-rewrite-75lb Imports
- rewrite wrong
import { rewrite } from 'koa-rewrite'; import * as rewrite from 'koa-rewrite';correctimport rewrite from 'koa-rewrite'; - rewrite wrong
const { rewrite } = require('koa-rewrite'); const rewrite = require('koa-rewrite').default;correctconst rewrite = require('koa-rewrite');
Quickstart
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)`);
});