{"id":17283,"library":"koa-proxies","title":"Koa HTTP Proxy Middleware","description":"`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.","status":"maintenance","version":"0.12.4","language":"javascript","source_language":"en","source_url":"https://github.com/vagusX/koa-proxies","tags":["javascript","koa","middleware","proxy","proxies","typescript"],"install":[{"cmd":"npm install koa-proxies","lang":"bash","label":"npm"},{"cmd":"yarn add koa-proxies","lang":"bash","label":"yarn"},{"cmd":"pnpm add koa-proxies","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency required for the middleware to function within a Koa application.","package":"koa","optional":false}],"imports":[{"note":"The `proxy` function is the default export of the module, commonly used in ESM modules. Attempting to destructure it as a named import will result in `undefined`.","wrong":"import { proxy } from 'koa-proxies';","symbol":"proxy","correct":"import proxy from 'koa-proxies';"},{"note":"For CommonJS environments, `require()` is the standard way to import the middleware. Attempting an ESM `import` in a CJS file will cause a syntax error.","symbol":"proxy (CommonJS)","correct":"const proxy = require('koa-proxies');"},{"note":"TypeScript types for `KoaProxyOptions` are available since v0.11.0. Use `import type` for type-only imports to prevent potential bundling issues in certain build setups.","wrong":"import { KoaProxyOptions } } from 'koa-proxies';","symbol":"KoaProxyOptions","correct":"import type { KoaProxyOptions } from 'koa-proxies';"}],"quickstart":{"code":"import Koa from 'koa';\nimport proxy from 'koa-proxies';\nimport httpsProxyAgent from 'https-proxy-agent'; // Install if needed: npm i https-proxy-agent\n\nconst app = new Koa();\n\n// Example 1: Basic proxy for a fixed path\napp.use(proxy('/api', {\n  target: 'http://localhost:3001', // Your target API server\n  changeOrigin: true, // Changes the origin of the host header to the target URL\n  rewrite: path => path.replace('/api', ''), // Rewrites the path from /api/users to /users\n  logs: true // Enables logging of proxy requests to console\n}));\n\n// Example 2: Dynamic proxy with path parameters\napp.use(proxy('/users/:id', (params, ctx) => {\n  return {\n    target: 'https://jsonplaceholder.typicode.com', // A public API for testing\n    changeOrigin: true,\n    rewrite: () => `/users/${params.id}`, // Dynamically rewrite path based on URL parameter\n    logs: (ctx, target) => {\n      console.log(`[Proxy Log] ${ctx.method} ${ctx.path} -> ${target}`);\n    },\n    // Example of using a proxy agent (install 'https-proxy-agent' if needed)\n    // agent: new httpsProxyAgent('http://your.proxy.server:port') // Remove if not using a proxy agent\n  };\n}));\n\napp.listen(3000, () => {\n  console.log('Koa proxy server listening on http://localhost:3000');\n  console.log('Try visiting http://localhost:3000/api/posts/1 (proxies to http://localhost:3001/posts/1)');\n  console.log('Or http://localhost:3000/users/1 (proxies to https://jsonplaceholder.typicode.com/users/1)');\n});","lang":"typescript","description":"Demonstrates basic and dynamic proxy configuration for a Koa application, including path rewriting, origin modification, custom logging, and path parameter handling."},"warnings":[{"fix":"Always ensure `app.use(proxy(...))` middleware is registered *before* `app.use(bodyParser())` or similar body-parsing middleware.","message":"Placing `koa-proxies` after `koa-bodyparser` (or any other middleware that consumes the request body stream) in the middleware chain can lead to requests hanging or unexpected behavior, especially for POST/PUT requests with bodies.","severity":"gotcha","affected_versions":">=0.5.0"},{"fix":"While this change is mostly internal, applications with highly customized `rewrite` functions or those performing complex URL manipulations should verify compatibility when upgrading from versions prior to 0.9.0.","message":"The internal path resolution logic was updated in `v0.9.0` to utilize the modern `URL` constructor instead of the deprecated Node.js `url.resolve` method.","severity":"breaking","affected_versions":">=0.9.0"},{"fix":"Upgrade to `v0.6.1` or later to ensure event listeners are correctly registered only once per proxy instance.","message":"Prior to `v0.6.1`, there was a bug where `http-proxy` events (e.g., `error`, `proxyReq`, `proxyRes`) were registered multiple times, which could potentially lead to memory leaks or incorrect event handling logic.","severity":"gotcha","affected_versions":"<=0.6.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure `koa-proxies` middleware is always applied before any middleware that parses or consumes the request body, such as `koa-bodyparser`. For example: `app.use(proxy('/api', {...})); app.use(bodyParser());`","cause":"`koa-proxies` is placed after `koa-bodyparser` or a similar body-parsing middleware, causing the request stream to be consumed before `koa-proxies` can process it.","error":"TypeError: ctx.request.body is undefined"},{"fix":"Verify that the backend service (e.g., `http://localhost:3001` in the quickstart) is actively running and reachable from the server hosting your Koa application. Check network configurations, firewall rules, or DNS settings if the target is remote.","cause":"The target server specified in the `options.target` configuration is not running, is inaccessible, or is listening on a different address/port than configured.","error":"Proxy error: connect ECONNREFUSED"},{"fix":"Implement robust error handling within the `options.events.error` callback. Before sending a response in the error handler, check `res.headersSent` to avoid attempting to set headers on an already-responded stream. For example: `if (!res.headersSent) { res.writeHead(500); res.end('Proxy error'); }`","cause":"This typically occurs when a proxy request fails, and an error handler attempts to send a response after the `http-proxy` library has already sent headers or a partial response.","error":"Error: Can't set headers after they are sent."}],"ecosystem":"npm","meta_description":null}