{"id":17017,"library":"http-proxy-middleware","title":"Node.js HTTP Proxy Middleware","description":"http-proxy-middleware is a robust and flexible Node.js library designed to easily set up reverse proxies within various HTTP server frameworks such as Express, Connect, Next.js, Fastify, and Polka. It leverages http-proxy under the hood, providing a 'one-liner' API to proxy requests, handle WebSockets, rewrite paths, and modify requests/responses. The current stable major version is 3.x (specifically v3.0.5 as of recent updates), with v4.0.0 actively under development in beta, introducing some breaking changes and refinements. The library is known for its ease of integration and comprehensive configuration options, making it a popular choice for development environments and API gateway setups where requests need to be routed to different backend services. Patch releases are frequent, addressing bugs and minor improvements.","status":"active","version":"3.0.5","language":"javascript","source_language":"en","source_url":"https://github.com/chimurai/http-proxy-middleware","tags":["javascript","reverse","proxy","middleware","http","https","connect","express","fastify","typescript"],"install":[{"cmd":"npm install http-proxy-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add http-proxy-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add http-proxy-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core library for proxying HTTP requests.","package":"http-proxy","optional":false},{"reason":"Used for WebSocket proxying functionality.","package":"ws","optional":false}],"imports":[{"note":"Primary export for creating a proxy middleware function. CommonJS users should use named require pattern.","wrong":"const createProxyMiddleware = require('http-proxy-middleware');","symbol":"createProxyMiddleware","correct":"import { createProxyMiddleware } from 'http-proxy-middleware';"},{"note":"Type import for configuration options. Use 'type' keyword for TypeScript.","wrong":"import { Options } from 'http-proxy-middleware';","symbol":"Options","correct":"import type { Options } from 'http-proxy-middleware';"},{"note":"This function was deprecated and completely removed in v4.0.0-beta.0. Projects on v3.x or older should migrate to `createProxyMiddleware`.","wrong":"import { legacyCreateProxyMiddleware } from 'http-proxy-middleware';","symbol":"legacyCreateProxyMiddleware","correct":"This symbol is removed in v4.0.0-beta.0. Use `createProxyMiddleware` instead."}],"quickstart":{"code":"import express from 'express';\nimport { createProxyMiddleware, Options } from 'http-proxy-middleware';\n\nconst app = express();\nconst port = 3000;\n\n// Configuration for the proxy middleware\nconst apiProxyOptions: Options = {\n  target: 'http://jsonplaceholder.typicode.com', // target host\n  changeOrigin: true, // needed for virtual hosted sites\n  ws: true, // proxy websockets\n  pathRewrite: {\n    '^/api': '', // rewrite path: remove `/api` prefix when forwarding to target\n  },\n  onProxyReq: (proxyReq, req, res) => {\n    // Optional: Log proxy request details or modify headers\n    console.log(`[Proxy] Proxying request: ${req.method} ${req.url} -> ${proxyReq.path}`);\n  },\n  onProxyRes: (proxyRes, req, res) => {\n    // Optional: Log proxy response details or modify response headers\n    console.log(`[Proxy] Received response for: ${req.url} with status: ${proxyRes.statusCode}`);\n  },\n  onError: (err, req, res, target) => {\n    console.error(`[Proxy Error] ${err.message}`);\n    res.status(500).send('Proxy Error');\n  }\n};\n\n// Apply the proxy middleware to '/api' route\napp.use('/api', createProxyMiddleware(apiProxyOptions));\n\n// Basic route for the main application\napp.get('/', (req, res) => {\n  res.send('Hello from the main application!');\n});\n\napp.listen(port, () => {\n  console.log(`Server listening at http://localhost:${port}`);\n  console.log(`Try accessing http://localhost:${port}/api/todos/1`);\n});\n\n// To run this:\n// 1. npm init -y\n// 2. npm install express http-proxy-middleware @types/express @types/http-proxy-middleware typescript ts-node\n// 3. Add \"start\": \"ts-node app.ts\" to package.json scripts\n// 4. npm start","lang":"typescript","description":"Sets up an Express server that proxies requests starting with `/api` to 'jsonplaceholder.typicode.com', demonstrating path rewriting, WebSocket support, and custom event handlers."},"warnings":[{"fix":"Replace `legacyCreateProxyMiddleware(...)` with `createProxyMiddleware(...)`. The options object structure remains largely compatible.","message":"The `legacyCreateProxyMiddleware` function has been removed. Users should migrate to `createProxyMiddleware` for all new and existing proxy configurations.","severity":"breaking","affected_versions":">=4.0.0-beta.0"},{"fix":"Ensure your Node.js environment is at least version `14.15.0`, `16.10.0`, or `18.0.0` or newer. Upgrade Node.js if necessary.","message":"Node.js engine requirements have been updated. Older Node.js versions are no longer supported.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Always set `changeOrigin: true` in your proxy options unless you specifically need to preserve the original `Host` header.","message":"The `changeOrigin` option is crucial for correctly proxying to virtual hosted sites or APIs that rely on the `Host` header. Failing to set it can lead to 404s or incorrect routing on the target server.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure `http-proxy-middleware` is applied *before* any body parsing middleware that it should bypass. Alternatively, set `options.router` and `options.onProxyReq` with `fixRequestBody: true` to ensure the body is properly forwarded.","message":"When proxying requests that contain a body (POST, PUT), if you have body parsing middleware (e.g., `express.json()`, `express.urlencoded()`) applied *before* `http-proxy-middleware`, the proxy might receive an empty body because the parsing middleware has consumed it. Use `fixRequestBody` option if necessary.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure `createProxyMiddleware` is called with a valid context string/array or an options object. Example: `app.use('/api', createProxyMiddleware({ target: 'http://localhost:5000' }));`","cause":"`createProxyMiddleware` was called with invalid arguments or no arguments, returning `undefined` instead of a function.","error":"TypeError: app.use() requires a middleware function"},{"fix":"Verify that your target server is running and accessible from where your Node.js application is running. Check the `target` URL for typos and correct port.","cause":"The target server specified in `options.target` is not running or is unreachable at the given address and port.","error":"Proxy error: connect ECONNREFUSED"},{"fix":"Double-check your `pathRewrite` regular expressions and replacement strings to ensure they always resolve to a valid string. For object-based rewrites, verify the keys match the incoming path segments.","cause":"Often related to incorrect `pathRewrite` configuration, where the rewrite function or object results in an undefined path.","error":"Error: The 'path' argument must be of type string. Received type undefined"},{"fix":"Ensure custom `onProxyReq` or `onProxyRes` handlers do not implicitly or explicitly send responses. If you need to handle errors or custom responses, do so before the proxy sends its own response, or ensure your custom handlers are aware of the proxy's lifecycle.","cause":"This error typically occurs when your application attempts to send a response or modify headers after the proxy has already initiated a response to the client.","error":"Error: Can't set headers after they are sent to the client."}],"ecosystem":"npm","meta_description":null}