{"id":16071,"library":"http-proxy","title":"Node.js HTTP/WebSocket Programmable Proxy","description":"http-proxy is a robust and programmable HTTP proxying library for Node.js, designed to facilitate the creation of components such as reverse proxies and load balancers. It offers comprehensive support for both HTTP(S) and WebSockets. The current stable version is 1.18.1. While its release cadence is not rapid, the project undergoes periodic maintenance, as highlighted by the 1.17.0 release which delivered numerous bug fixes and feature additions, indicating active, albeit slower, development. A key differentiator is its `createProxyServer` factory, which returns a flexible proxy instance, allowing developers to customize request and response pipelines for fine-grained control over proxied traffic, making it suitable for complex proxying scenarios beyond basic URL forwarding.","status":"active","version":"1.18.1","language":"javascript","source_language":"en","source_url":"https://github.com/http-party/node-http-proxy","tags":["javascript"],"install":[{"cmd":"npm install http-proxy","lang":"bash","label":"npm"},{"cmd":"yarn add http-proxy","lang":"bash","label":"yarn"},{"cmd":"pnpm add http-proxy","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"This imports the entire CommonJS module object, which contains the `createProxyServer` factory function as a property.","wrong":"import httpProxy from 'http-proxy';","symbol":"httpProxy (Module Object, CommonJS)","correct":"const httpProxy = require('http-proxy');"},{"note":"For ESM, the CommonJS module is typically imported as a default export. The `createProxyServer` function is then accessed as `httpProxy.createProxyServer`.","wrong":"const httpProxy = require('http-proxy');","symbol":"httpProxy (Module Object, ESM)","correct":"import httpProxy from 'http-proxy';"},{"note":"This directly destructures the `createProxyServer` function from the CommonJS module object for convenience.","wrong":"const createProxyServer = require('http-proxy').createProxyServer;","symbol":"createProxyServer (Factory Function, CommonJS Destructuring)","correct":"const { createProxyServer } = require('http-proxy');"},{"note":"This assumes `http-proxy` provides a named export for `createProxyServer` for direct ESM access. If not, use `import httpProxy from 'http-proxy'; const { createProxyServer } = httpProxy;`.","wrong":"import createProxyServer from 'http-proxy';","symbol":"createProxyServer (Factory Function, ESM Named Import)","correct":"import { createProxyServer } from 'http-proxy';"}],"quickstart":{"code":"const http = require('http');\nconst httpProxy = require('http-proxy');\n\n// --- Target Server ---\nconst targetPort = 9000;\nconst targetServer = http.createServer((req, res) => {\n  console.log(`[Target] Received request for: ${req.url}`);\n  res.writeHead(200, { 'Content-Type': 'text/plain' });\n  res.end(`Hello from Target Server! You requested ${req.url}\\n`);\n});\n\ntargetServer.listen(targetPort, () => {\n  console.log(`[Target] Server listening on http://localhost:${targetPort}`);\n});\n\n// --- Proxy Server ---\nconst proxyPort = 8000;\nconst proxy = httpProxy.createProxyServer({\n  target: `http://localhost:${targetPort}`,\n  ws: true // Enable WebSocket proxying\n});\n\nproxy.on('error', (err, req, res) => {\n  console.error('[Proxy] HTTP error:', err.message);\n  if (!res.headersSent) {\n    res.writeHead(500, { 'Content-Type': 'text/plain' });\n    res.end('Proxy Error: Could not reach the target.');\n  }\n});\n\nproxy.on('proxyReq', (proxyReq, req, res, options) => {\n  console.log(`[Proxy] Proxying HTTP request: ${req.method} ${req.url}`);\n});\n\nproxy.on('proxyRes', (proxyRes, req, res) => {\n  console.log(`[Proxy] Response from target: ${proxyRes.statusCode}`);\n});\n\nconst proxyServer = http.createServer((req, res) => {\n  // Handle regular HTTP(S) requests\n  proxy.web(req, res);\n});\n\nproxyServer.on('upgrade', (req, socket, head) => {\n  // Handle WebSocket upgrade requests\n  console.log(`[Proxy] Proxying WebSocket upgrade for: ${req.url}`);\n  proxy.ws(req, socket, head);\n});\n\nproxyServer.listen(proxyPort, () => {\n  console.log(`[Proxy] Server listening on http://localhost:${proxyPort}`);\n  console.log(`\nTest HTTP by visiting:   http://localhost:${proxyPort}/any/path`);\n  console.log(`Test WebSocket (e.g., with 'wscat'): wscat -c ws://localhost:${proxyPort}`);\n});\n\n// Clean up on exit\nprocess.on('SIGINT', () => {\n  console.log('\\n[App] Shutting down servers...');\n  proxyServer.close(() => console.log('[Proxy] Server closed.'));\n  targetServer.close(() => console.log('[Target] Server closed.'));\n  process.exit(0);\n});","lang":"javascript","description":"This example sets up a basic `http-proxy` server on port 8000 that forwards both HTTP and WebSocket requests to a target server running on port 9000. It includes basic error handling and logging."},"warnings":[{"fix":"Refer to the `UPGRADING.md` document linked in the package's README for detailed migration steps when upgrading from pre-1.0.0 versions.","message":"Major breaking changes were introduced after the 0.8.x series. Direct migration from these older versions to 1.x.x without consulting the `UPGRADING.md` guide will likely result in compatibility issues.","severity":"breaking","affected_versions":"<1.0.0"},{"fix":"Implement `proxy.on('error', (err, req, res) => { /* handle error */ });` or ensure an error callback is passed to proxy methods like `proxy.web(req, res, options, (err) => { /* handle error */ });`.","message":"Proxy errors must be explicitly handled, either by listening to the `error` event on the proxy instance or by providing an error callback to `proxy.web` or `proxy.ws` calls. Unhandled errors can lead to ungraceful server shutdowns or unresponsiveness.","severity":"gotcha","affected_versions":">=0.8.0"},{"fix":"Always ensure `target` is correctly specified in the options object, e.g., `{ target: 'http://localhost:8080' }`, or passed directly to the `web`/`ws` methods.","message":"The `target` option is mandatory for `proxy.web` and `proxy.ws` calls, specifying the destination URL for the proxied request. Omitting or providing an invalid target will result in connection errors and prevent successful proxying.","severity":"gotcha","affected_versions":">=0.8.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Ensure the `target` option is a string with a valid protocol and host (e.g., `'http://localhost:3000'`) or an object specifying `host` and `port`.","cause":"The `target` option in the `createProxyServer` constructor or `proxy.web`/`proxy.ws` calls is either missing or malformed.","error":"Error: Must provide a target protocol and host (e.g. http://localhost)"},{"fix":"First, create a proxy instance: `const proxy = httpProxy.createProxyServer(options);`. Then, call `proxy.web(req, res);` on that instance.","cause":"This usually means you're trying to call `web` on the `httpProxy` module object itself (e.g., `httpProxy.web(...)`) rather than on an instance created by `httpProxy.createProxyServer()`.","error":"TypeError: proxy.web is not a function"},{"fix":"Verify that your target server is actively running and listening on the specified host and port. Check firewall rules if the target is on a different machine or network.","cause":"The target server specified in the `target` option is not running or is inaccessible at the given host and port, preventing `http-proxy` from establishing a connection.","error":"Error: connect ECONNREFUSED 127.0.0.1:9000"}],"ecosystem":"npm"}