Koa Better HTTP Proxy
koa-better-http-proxy is an HTTP proxy middleware for Koa applications, enabling requests to be forwarded to a different host and the response passed back to the client. The current stable version is 0.2.10. This package has a moderate release cadence, with several minor updates and bug fixes released within the last year, indicating active maintenance. Key differentiators include its foundation on `express-http-proxy`, support for asynchronous path resolvers (`proxyReqPathResolver`) and response/header decorators (`userResDecorator`, `userResHeadersDecorator`), and automatic handling of gzipped responses. It provides fine-grained control over request and response modification, header stripping, and custom `http.Agent` usage, making it suitable for complex proxying scenarios within a Koa ecosystem.
Common errors
-
TypeError: proxy is not a function
cause Incorrect import statement for the default export.fixFor ES Modules, use `import proxy from 'koa-better-http-proxy';`. For CommonJS, use `const proxy = require('koa-better-http-proxy');`. -
TypeError: app.use is not a function
cause Koa application instance is not correctly initialized or the middleware is being applied to a non-Koa object.fixEnsure you have `import Koa from 'koa';` and `const app = new Koa();` at the start of your Koa application setup, and that `koa` is installed (`npm install koa`). -
Property 'ctx' does not exist on type 'Context'.
cause Using an outdated or incompatible TypeScript type definition for Koa's Context object, or a version mismatch between Koa and the proxy types.fixEnsure `koa-better-http-proxy` is at least v0.2.2 for TypeScript types, and that `koa` and `@types/koa` are correctly installed and aligned with your Koa version. Sometimes, reinstalling `@types/koa` can resolve such issues. -
Error: Cannot find module 'koa'
cause The `koa` package is not installed as a dependency in the project.fixInstall Koa: `npm install koa` or `yarn add koa`.
Warnings
- breaking The `memoizeHost` option was removed as it was never truly supported. Code relying on this option will break.
- breaking Headers could leak across requests in certain scenarios, leading to incorrect or unintended behavior for subsequent requests using the same proxy instance.
- gotcha The `proxyReqOptDecorator` function does not allow modification of the request path. Attempts to change the path within this decorator will not take effect.
- gotcha By default, `Connection: close` is no longer set on proxy requests. If your backend relies on this header for specific connection management, its absence might alter behavior.
- gotcha The `userResDecorator` and `userResHeadersDecorator` functions pass `proxyRes` and `ctx` by reference. While this *can* be exploited to modify response headers directly, it is not a stable API and future releases may remove this 'exploit'.
Install
-
npm install koa-better-http-proxy -
yarn add koa-better-http-proxy -
pnpm add koa-better-http-proxy
Imports
- proxy
import { proxy } from 'koa-better-http-proxy';import proxy from 'koa-better-http-proxy';
- proxy
const { proxy } = require('koa-better-http-proxy');const proxy = require('koa-better-http-proxy'); - ProxyOptions
import type { ProxyOptions, Context } from 'koa-better-http-proxy';
Quickstart
import Koa from 'koa';
import proxy from 'koa-better-http-proxy';
import Router from '@koa/router';
import { URL } from 'url';
const app = new Koa();
const router = new Router();
router.all('/api/(.*)', proxy('httpbin.org', {
port: 80,
https: false,
proxyReqPathResolver: (ctx) => {
const url = new URL(ctx.url, `http://${ctx.host}`);
console.log(`Proxying request path: ${url.pathname}${url.search}`);
return `/anything${url.pathname.substring('/api'.length)}${url.search}`;
},
userResDecorator: (proxyRes, proxyResData, ctx) => {
const data = JSON.parse(proxyResData.toString('utf8'));
data.proxiedBy = 'koa-better-http-proxy';
data.originalUrl = ctx.url;
return JSON.stringify(data);
}
}));
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000, () => {
console.log('Koa proxy server listening on port 3000');
console.log('Try: curl http://localhost:3000/api/my-test?q=hello');
});