Koa Better HTTP Proxy

0.2.10 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

This example sets up a Koa server with `koa-better-http-proxy` to proxy requests starting with `/api` to `httpbin.org/anything`. It demonstrates path rewriting using `proxyReqPathResolver` and modifying the response body with `userResDecorator`.

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');
});

view raw JSON →