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.
npm install http-proxy-middlewareVerified import paths — ran on the pinned version, not inferred.
Sets up an Express server that proxies requests starting with `/api` to 'jsonplaceholder.typicode.com', demonstrating path rewriting, WebSocket support, and custom event handlers.
Replace `legacyCreateProxyMiddleware(...)` with `createProxyMiddleware(...)`. The options object structure remains largely compatible.
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.
Always set `changeOrigin: true` in your proxy options unless you specifically need to preserve the original `Host` header.
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.
Ensure `createProxyMiddleware` is called with a valid context string/array or an options object. Example: `app.use('/api', createProxyMiddleware({ target: 'http://localhost:5000' }));`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.
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.
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.