koa2-proxy-middleware
raw JSON → 0.0.4 verified Sat Apr 25 auth: no javascript
A Koa2 middleware wrapping http-proxy-middleware to proxy requests based on URL patterns using path-to-regexp. Version 0.0.4 is the current stable release; the package is infrequently updated. It provides a declarative way to configure multiple proxy targets in Koa2 applications, leveraging the mature http-proxy-middleware for WebSocket and HTTP proxying. Unlike generic Koa proxy middlewares, it uses path-to-regexp for route matching, allowing dynamic route parameters. It ships TypeScript definitions.
Common errors
error Cannot find module 'koa2-proxy-middleware' ↓
cause Package not installed or not in node_modules.
fix
Run
npm install koa2-proxy-middleware. error TypeError: proxy is not a function ↓
cause Incorrect import style (e.g., destructured import when package exports a single function).
fix
Use
const proxy = require('koa2-proxy-middleware'). error Error: Cannot find module 'http-proxy-middleware' ↓
cause Dependency not installed automatically when peer dependency.
fix
Install http-proxy-middleware explicitly:
npm install http-proxy-middleware. Warnings
breaking Package is CommonJS-only; cannot be imported as ESM in Node.js without bundler. ↓
fix Use require() or configure module resolution to allow CommonJS.
gotcha Bodyparser middleware must be placed after proxy middleware for POST requests to avoid delays. ↓
fix Ensure proxy middleware is used before koa-bodyparser or similar body parsers.
deprecated path-to-regexp v2 used internally; newer versions may have breaking changes. ↓
fix No action needed unless you rely on specific regexp behavior.
gotcha Options key patterns are converted to regexp using path-to-regexp; non-standard patterns may not match as expected. ↓
fix Ensure patterns follow path-to-regexp syntax (e.g., '/:param', '/(.*)').
Install
npm install koa2-proxy-middleware yarn add koa2-proxy-middleware pnpm add koa2-proxy-middleware Imports
- default wrong
import proxy from 'koa2-proxy-middleware'correctconst proxy = require('koa2-proxy-middleware') - default
import proxy from 'koa2-proxy-middleware' - ProxyMiddleware
import { ProxyMiddleware } from 'koa2-proxy-middleware'
Quickstart
const Koa = require('koa');
const proxy = require('koa2-proxy-middleware');
const app = new Koa();
const options = {
targets: {
'/api/(.*)': {
target: 'http://httpbin.org',
changeOrigin: true,
},
},
};
app.use(proxy(options));
app.listen(3000);
console.log('Proxy server running on port 3000');