Koa HTTP Proxy Middleware

0.12.4 · maintenance · verified Wed Apr 22

`koa-proxies` is an HTTP proxy middleware specifically designed for Koa@2.x applications, providing robust proxying capabilities powered by the underlying `http-proxy` library. It enables developers to easily route incoming requests to different target servers, a common pattern for API forwarding, bypassing CORS restrictions during development, or orchestrating microservices. The library currently stands at version 0.12.4. While its latest release dates indicate a more maintenance-focused cadence rather than active feature development (last significant features around 2020), it remains a functional and widely used choice for Koa projects. Key differentiators include its flexible option handling, allowing both static configurations and dynamic determination of proxy settings via a function, and integrated support for `path-match` for advanced routing logic. It also provides built-in TypeScript type definitions since version 0.11.0, enhancing developer experience in TypeScript-based Koa applications.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic and dynamic proxy configuration for a Koa application, including path rewriting, origin modification, custom logging, and path parameter handling.

import Koa from 'koa';
import proxy from 'koa-proxies';
import httpsProxyAgent from 'https-proxy-agent'; // Install if needed: npm i https-proxy-agent

const app = new Koa();

// Example 1: Basic proxy for a fixed path
app.use(proxy('/api', {
  target: 'http://localhost:3001', // Your target API server
  changeOrigin: true, // Changes the origin of the host header to the target URL
  rewrite: path => path.replace('/api', ''), // Rewrites the path from /api/users to /users
  logs: true // Enables logging of proxy requests to console
}));

// Example 2: Dynamic proxy with path parameters
app.use(proxy('/users/:id', (params, ctx) => {
  return {
    target: 'https://jsonplaceholder.typicode.com', // A public API for testing
    changeOrigin: true,
    rewrite: () => `/users/${params.id}`, // Dynamically rewrite path based on URL parameter
    logs: (ctx, target) => {
      console.log(`[Proxy Log] ${ctx.method} ${ctx.path} -> ${target}`);
    },
    // Example of using a proxy agent (install 'https-proxy-agent' if needed)
    // agent: new httpsProxyAgent('http://your.proxy.server:port') // Remove if not using a proxy agent
  };
}));

app.listen(3000, () => {
  console.log('Koa proxy server listening on http://localhost:3000');
  console.log('Try visiting http://localhost:3000/api/posts/1 (proxies to http://localhost:3001/posts/1)');
  console.log('Or http://localhost:3000/users/1 (proxies to https://jsonplaceholder.typicode.com/users/1)');
});

view raw JSON →