{"id":27969647,"url":"https://github.com/sagemathinc/http-proxy-3","last_synced_at":"2026-04-30T09:33:44.143Z","repository":{"id":291805583,"uuid":"978815544","full_name":"sagemathinc/http-proxy-3","owner":"sagemathinc","description":"Modern rewrite of node-proxy (the original nodejs http proxy server)","archived":false,"fork":false,"pushed_at":"2025-12-01T14:41:41.000Z","size":1736,"stargazers_count":100,"open_issues_count":14,"forks_count":15,"subscribers_count":4,"default_branch":"main","last_synced_at":"2026-04-25T18:10:03.620Z","etag":null,"topics":["nodejs","proxy"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/http-proxy-3","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sagemathinc.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-05-06T14:49:46.000Z","updated_at":"2026-04-23T08:47:53.000Z","dependencies_parsed_at":"2025-05-07T21:49:52.985Z","dependency_job_id":"cb668834-f6c1-4b54-b67e-687b87044fd4","html_url":"https://github.com/sagemathinc/http-proxy-3","commit_stats":null,"previous_names":["sagemathinc/node-proxy-2","sagemathinc/http-proxy-2","sagemathinc/http-proxy-3"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/sagemathinc/http-proxy-3","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sagemathinc%2Fhttp-proxy-3","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sagemathinc%2Fhttp-proxy-3/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sagemathinc%2Fhttp-proxy-3/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sagemathinc%2Fhttp-proxy-3/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sagemathinc","download_url":"https://codeload.github.com/sagemathinc/http-proxy-3/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sagemathinc%2Fhttp-proxy-3/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32460781,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-29T22:27:22.272Z","status":"online","status_checked_at":"2026-04-30T02:00:05.929Z","response_time":57,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["nodejs","proxy"],"created_at":"2025-05-07T21:49:49.643Z","updated_at":"2026-04-30T09:33:44.135Z","avatar_url":"https://github.com/sagemathinc.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# http-proxy-3\n\n[![Build package and run tests](https://github.com/sagemathinc/http-proxy-3/actions/workflows/test.yml/badge.svg)](https://github.com/sagemathinc/http-proxy-3/actions/workflows/test.yml)\n\n**THIS IS MAINTAINED AND READY TO USE IN PRODUCTION. Please use it!**\n\n- Used in production by:\n  - [CoCalc](https://cocalc.com)\n  - [JupyterHub](https://jupyter.org/hub)\n  - [Vite](https://vite.dev/)\n\nhttp\\-proxy\\-3 is a modern API compatible rewrite of\n[http\\-proxy](https://github.com/http-party/node-http-proxy), the original nodejs\nhttp proxy server. `http-proxy-3` is an HTTP programmable proxying library that\nsupports http/https and websockets. It is also suitable for implementing components\nsuch as reverse proxies and load balancers. It's main strength is that you can combine application logic written in Javascript with a proxy server, unlike what\ncan be done using nginx or haproxy.\n\n**PR's welcome!**\n\nContributors:\n\n- [William](https://wstein.org/) [Stein](https://github.com/williamstein) -- lead dev; started this fork and did the initial Typescript rewrite, etc.\n- [sapphi-red](https://green.sapphi.red/about) -- greatly improved Typescript support to prepare http-proxy-3 for use in [Vite](https://vite.dev/)\n- [ImranR-TI](https://github.com/ImranR-TI) -- very helpful bug reports\n- [Corvince](https://github.com/corvince) -- HTTP/2 Support\n- Everybody who ever contributed to [http-proxy](https://www.npmjs.com/package/http-proxy)\n\n**Status:**\n\nOctober 8, 2025 STATUS compared to [http-proxy](https://www.npmjs.com/package/http-proxy) and [httpxy](https://www.npmjs.com/package/httpxy):\n\n- Library entirely rewritten in Typescript in a modern style, with many typings added internally and strict mode enabled.\n- **HTTP/2 Support**: Full HTTP/2 support via fetch API with callback-based request/response lifecycle hooks.\n- All dependent packages updated to latest versions, addressing all security vulnerabilities according to `pnpm audit`.\n- Code rewritten to not use deprecated/insecure API's, e.g., using `URL` instead of `parse`.\n- Fixed multiple socket leaks in the Websocket proxy code, going beyond [http-proxy-node16](https://www.npmjs.com/package/http-proxy-node16) to also instrument and logging socket counts. Also fixed an issue with uncatchable errors when using websockets.\n- Switch to pnpm for development.\n- More jest unit tests than both http-proxy and httpxy: converted all the http-proxy examples into working unit tests that they actually work (http-proxy's unit tests just setup the examples in many cases, but didn't test that they actually work). Also httpxy seems to have almost no tests. These tests should make contributing PR's much easier.\n- [Partial HTTP2 support](https://github.com/sagemathinc/http-proxy-3/pull/33).\n- Addressed [this vulnerability](https://github.com/http-party/node-http-proxy/issues/1647).\n\n**Motivation:** http-proxy is one of the oldest and most famous nodejs modules, and it gets downloaded around 15 million times a week, and I've loved using it for years. Unfortunately, it is [unmaintained](https://github.com/http-party/node-http-proxy/issues/1687), it has significant leaks that [regularly crash production servers](https://github.com/jupyterhub/configurable-http-proxy/issues/434), and is written in ancient untyped Javascript. The maintainers have long since stopped responding, so there is no choice but to fork and start over. I wanted to do my part to help maintain the open source ecosystem, hence this library. I hope you find it useful.\n\n**Performance:**\n\nI've been adding load tests to the unit tests in various places. Generally speaking on a local machine over localhost the penalty to using the proxy server is that **things take about twice as long**. That's not surprising because it's twice as much work being done.\n\n**Related Projects:**\n\n- https://github.com/unjs/httpxy: it has the same motivation as this project -- it's a modern maintained rewrite of http-proxy. Unfortunately, it seems to have [very little unit testing](https://github.com/unjs/httpxy/tree/main/test). In http-proxy-3 (and the original http-proxy), there's an order of magnitude more unit test code than code in the actual library.\n\n**Officially supported platforms:**\n\nWe run GitHUB CI on the following:\n\n- nodejs versions 20, 22, and 24\n\n**Development:**\n\n```sh\ngit clone https://github.com/sagemathinc/http-proxy-3.git\ncd http-proxy-3\npnpm install\npnpm build\npnpm test\n```\n\nThen do\n\n```\npnpm tsc\n```\n\nand make changes to code under lib/.\n\nCode Style: use prettier with the defaults.\n\n[![Build package and run tests](https://github.com/sagemathinc/http-proxy-3/actions/workflows/test.yml/badge.svg)](https://github.com/sagemathinc/http-proxy-3/actions/workflows/test.yml)\n\n## User's Guide\n\nThis is the original user's guide, but with various updates.\n\n- [Installation](#installation)\n- [Core Concept](#core-concept)\n- [Use Cases](#use-cases)\n  - [Setup a basic stand-alone proxy server](#setup-a-basic-stand-alone-proxy-server)\n  - [Setup a stand-alone proxy server with custom server logic](#setup-a-stand-alone-proxy-server-with-custom-server-logic)\n  - [Setup a stand-alone proxy server with proxy request header re-writing](#setup-a-stand-alone-proxy-server-with-proxy-request-header-re-writing)\n  - [Modify a response from a proxied server](#modify-a-response-from-a-proxied-server)\n  - [Setup a stand-alone proxy server with latency](#setup-a-stand-alone-proxy-server-with-latency)\n  - [Using HTTPS](#using-https)\n  - [Proxying WebSockets](#proxying-websockets)\n  - [HTTP/2 Support with Fetch](#http2-support-with-fetch)\n- [Options](#options)\n- [Configuration Compatibility](#configuration-compatibility)\n- [Listening for proxy events](#listening-for-proxy-events)\n- [Shutdown](#shutdown)\n- [Miscellaneous](#miscellaneous)\n  - [Test](#test)\n  - [ProxyTable API](#proxytable-api)\n  - [Logo](#logo)\n- [Contributing and Issues](#contributing-and-issues)\n- [License](#license)\n\n### Installation\n\n`npm install http-proxy-3 --save`\n\n**[Back to top](#table-of-contents)**\n\n### Core Concept\n\nA new proxy is created by calling `createProxyServer` and passing\nan `options` object as argument ([valid properties are available here](lib/http-proxy/index.ts))\n\n```js\nimport { createProxyServer } from \"http-proxy-3\";\nconst proxy = createProxyServer(options); // See below\n```\n\nhttp-proxy-3 supports two request processing paths:\n- **Native Path**: Uses Node.js native `http`/`https` modules (default)\n- **Fetch Path**: Uses fetch API for HTTP/2 support (when `fetch` option is provided)\n\nUnless listen(..) is invoked on the object, this does not create a webserver. See below.\n\nAn object is returned with four methods:\n\n- web `req, res, [options]` (used for proxying regular HTTP(S) requests)\n- ws `req, socket, head, [options]` (used for proxying WS(S) requests)\n- listen `port` (a function that wraps the object in a webserver, for your convenience)\n- close `[callback]` (a function that closes the inner webserver and stops listening on given port)\n\nIt is then possible to proxy requests by calling these functions\n\n```js\nhttp.createServer((req, res) =\u003e {\n  proxy.web(req, res, { target: \"http://mytarget.com:8080\" });\n});\n```\n\nErrors can be listened on either using the Event Emitter API\n\n```js\nproxy.on('error', (err) =\u003e {\n  ...\n});\n```\n\nor using the callback API\n\n```javascript\nproxy.web(req, res, { target: 'http://mytarget.com:8080' }, (err) =\u003e { ... });\n```\n\nWhen a request is proxied it follows two different pipelines ([available here](lib/http-proxy/passes))\nwhich apply transformations to both the `req` and `res` object.\nThe first pipeline (incoming) is responsible for the creation and manipulation of the stream that connects your client to the target.\nThe second pipeline (outgoing) is responsible for the creation and manipulation of the stream that, from your target, returns data\nto the client.\n\n**[Back to top](#table-of-contents)**\n\n### Use Cases\n\nThere are unit tested examples illustrating everything below in\nthe tests subdirectory.\n\n#### Setup a basic stand-alone proxy server\n\n```js\nimport * as http from \"node:http\";\nimport { createProxyServer } from \"http-proxy-3\";\n\n// Create your proxy server and set the target in the options.\ncreateProxyServer({ target: \"http://localhost:9000\" }).listen(8000); // See (†)\n\n// Create your target server\nhttp\n  .createServer((req, res) =\u003e {\n    res.writeHead(200, { \"Content-Type\": \"text/plain\" });\n    res.write(\n      \"request successfully proxied!\" +\n        \"\\n\" +\n        JSON.stringify(req.headers, true, 2),\n    );\n    res.end();\n  })\n  .listen(9000);\n```\n\n† Just like with the nodejs http module, invoking `listen(...)` triggers the creation of a web server. Otherwise, just the proxy instance is created, which is just a lightweight object with configuration. _If you call close on the proxy it is a no\\-op unless you have called listen._\n\n**[Back to top](#table-of-contents)**\n\n#### Setup a stand-alone proxy server with custom server logic\n\nThis example shows how you can proxy a request using your own HTTP server\nand also you can put your own logic to handle the request.\n\n```js\nimport * as http from \"node:http\";\nimport { createProxyServer } from \"http-proxy-3\";\n\n// Create a proxy server with custom application logic\nconst proxy = createProxyServer({});\n\n// Create your custom server and just call `proxy.web()` to proxy\n// a web request to the target passed in the options\n// also you can use `proxy.ws()` to proxy a websockets request\nconst server = http.createServer((req, res) =\u003e {\n  // You can define here your custom logic to handle the request\n  // and then proxy the request.\n  proxy.web(req, res, { target: \"http://127.0.0.1:5050\" });\n});\n\nconsole.log(\"listening on port 5050\");\nserver.listen(5050);\n```\n\n**[Back to top](#table-of-contents)**\n\n#### Setup a stand-alone proxy server with proxy request header re-writing\n\nThis example shows how you can proxy a request using your own HTTP server that\nmodifies the outgoing proxy request by adding a special header.\n\n##### Using Traditional Events (Native HTTP/HTTPS)\n\n```js\nimport * as http from \"node:http\";\nimport { createProxyServer } from \"http-proxy-3\";\n\n// Create a proxy server with custom application logic\nconst proxy = createProxyServer({});\n\n// To modify the proxy connection before data is sent, you can listen\n// for the 'proxyReq' event. When the event is fired, you will receive\n// the following arguments:\n// (http.ClientRequest proxyReq, http.IncomingMessage req,\n//  http.ServerResponse res, Object options). This mechanism is useful when\n// you need to modify the proxy request before the proxy connection\n// is made to the target.\nproxy.on(\"proxyReq\", (proxyReq, req, res, options, socket) =\u003e {\n  proxyReq.setHeader(\"X-Special-Proxy-Header\", \"foobar\");\n});\n\nconst server = http.createServer((req, res) =\u003e {\n  // You can define here your custom logic to handle the request\n  // and then proxy the request.\n  proxy.web(req, res, {\n    target: \"http://127.0.0.1:5050\",\n  });\n});\n\nconsole.log(\"listening on port 5050\");\nserver.listen(5050);\n```\n\n##### Using Callbacks (Fetch/HTTP/2)\n\n```js\nimport * as http from \"node:http\";\nimport { createProxyServer } from \"http-proxy-3\";\nimport { Agent } from \"undici\";\n\n// Create a proxy server with fetch and HTTP/2 support\nconst proxy = createProxyServer({\n  target: \"https://127.0.0.1:5050\",\n  fetchOptions: {\n    requestOptions: {dispatcher: new Agent({ allowH2: true })},\n    // Modify the request before it's sent\n    onBeforeRequest: async (requestOptions, req, res, options) =\u003e {\n      requestOptions.headers['X-Special-Proxy-Header'] = 'foobar';\n      requestOptions.headers['X-HTTP2-Enabled'] = 'true';\n    },\n    // Access the response after it's received\n    onAfterResponse: async (response, req, res, options) =\u003e {\n      console.log(`Proxied ${req.url} -\u003e ${response.status}`);\n    }\n  }\n});\n\nconst server = http.createServer((req, res) =\u003e {\n  // The headers are modified via the onBeforeRequest callback\n  proxy.web(req, res);\n});\n\nconsole.log(\"listening on port 5050\");\nserver.listen(5050);\n```\n\n**[Back to top](#table-of-contents)**\n\n#### Modify a response from a proxied server\n\nSometimes when you have received a HTML/XML document from the server of origin you would like to modify it before forwarding it on.\n\n[Harmon](https://github.com/No9/harmon) allows you to do this in a streaming style so as to keep the pressure on the proxy to a minimum.\n\n**[Back to top](#table-of-contents)**\n\n#### Setup a stand-alone proxy server with latency\n\n```js\nimport * as http from \"node:http\";\nimport { createProxyServer } from \"http-proxy-3\";\n\n// Create a proxy server with latency\nconst proxy = createProxyServer();\n\n// Create your server that makes an operation that waits a while\n// and then proxies the request\nhttp\n  .createServer((req, res) =\u003e {\n    // This simulates an operation that takes 500ms to execute\n    setTimeout(function () {\n      proxy.web(req, res, {\n        target: \"http://localhost:9008\",\n      });\n    }, 500);\n  })\n  .listen(8008);\n\n// Create your target server\nhttp\n  .createServer(function (req, res) {\n    res.writeHead(200, { \"Content-Type\": \"text/plain\" });\n    res.write(\n      \"request successfully proxied to: \" +\n        req.url +\n        \"\\n\" +\n        JSON.stringify(req.headers, true, 2),\n    );\n    res.end();\n  })\n  .listen(9008);\n```\n\n**[Back to top](#table-of-contents)**\n\n#### Using HTTPS\n\nYou can activate the validation of a secure SSL certificate to the target connection (avoid self-signed certs), just set `secure: true` in the options.\n\n##### HTTPS -\u003e HTTP\n\n```js\n// Create the HTTPS proxy server in front of a HTTP server\nhttpProxy\n  .createServer({\n    target: {\n      host: \"localhost\",\n      port: 9009,\n    },\n    ssl: {\n      key: fs.readFileSync(\"valid-ssl-key.pem\", \"utf8\"),\n      cert: fs.readFileSync(\"valid-ssl-cert.pem\", \"utf8\"),\n    },\n  })\n  .listen(8009);\n```\n\n##### HTTPS -\u003e HTTPS\n\n```js\n// Create the proxy server listening on port 443\nhttpProxy\n  .createServer({\n    ssl: {\n      key: fs.readFileSync(\"valid-ssl-key.pem\", \"utf8\"),\n      cert: fs.readFileSync(\"valid-ssl-cert.pem\", \"utf8\"),\n    },\n    target: \"https://localhost:9010\",\n    secure: true, // Depends on your needs, could be false.\n  })\n  .listen(443);\n```\n\n##### HTTP -\u003e HTTPS (using a PKCS12 client certificate)\n\n```js\n// Create an HTTP proxy server with an HTTPS target\nhttpProxy\n  .createProxyServer({\n    target: {\n      protocol: \"https:\",\n      host: \"my-domain-name\",\n      port: 443,\n      pfx: fs.readFileSync(\"path/to/certificate.p12\"),\n      passphrase: \"password\",\n    },\n    changeOrigin: true,\n  })\n  .listen(8000);\n```\n\n**[Back to top](#table-of-contents)**\n\n#### Proxying WebSockets\n\nYou can activate the websocket support for the proxy using `ws:true` in the options.\n\n```js\n// Create a proxy server for websockets\nhttpProxy\n  .createServer({\n    target: \"ws://localhost:9014\",\n    ws: true,\n  })\n  .listen(8014);\n```\n\nAlso you can proxy the websocket requests just calling the `ws(req, socket, head)` method.\n\n```js\nimport * as http from \"node:http\";\nimport { createProxyServer } from \"http-proxy-3\";\n\n// Setup our server to proxy standard HTTP requests\n\nconst proxy = createProxyServer({\n  target: {\n    host: \"localhost\",\n    port: 9015,\n  },\n});\nvar proxyServer = http.createServer((req, res) =\u003e {\n  proxy.web(req, res);\n});\n\n// Listen to the `upgrade` event and proxy the\n// WebSocket requests as well.\nproxyServer.on(\"upgrade\", (req, socket, head) =\u003e {\n  proxy.ws(req, socket, head);\n});\n\nproxyServer.listen(8015);\n```\n\n**[Back to top](#table-of-contents)**\n\n#### HTTP/2 Support with Fetch\n\n\u003e **⚠️ Experimental Feature**: The fetch code path for HTTP/2 support is currently experimental. While it provides HTTP/2 functionality and has comprehensive test coverage, the API and behavior may change in future versions. Use with caution in production environments.\n\nhttp-proxy-3 supports HTTP/2 through the native fetch API. When fetch is enabled, the proxy can communicate with HTTP/2 servers. The fetch code path is runtime-agnostic and works across different JavaScript runtimes (Node.js, Deno, Bun, etc.). However, this means HTTP/2 support depends on the runtime. Deno enables HTTP/2 by default, Bun currently does not and Node.js requires to set a different dispatcher. See next section for Node.js details.\n\n\n##### Basic HTTP/2 Setup\n\n```js\nimport { createProxyServer } from \"http-proxy-3\";\nimport { Agent, setGlobalDispatcher } from \"undici\";\n\n// Either enable HTTP/2 for all fetch operations\nsetGlobalDispatcher(new Agent({ allowH2: true }));\n\n// Or create a proxy with HTTP/2 support using fetch\nconst proxy = createProxyServer({\n  target: \"https://http2-server.example.com\",\n  fetchOptions: {\n    requestOptions: {dispatcher: new Agent({ allowH2: true })}\n  }\n});\n```\n\n##### Simple Fetch Enablement\n\n```js\n// Shorthand to enable fetch with defaults\nconst proxy = createProxyServer({\n  target: \"https://http2-server.example.com\",\n  fetch  // Uses default fetch configuration\n});\n```\n\n##### Advanced Configuration with Callbacks\n\n```js\nconst proxy = createProxyServer({\n  target: \"https://api.example.com\",\n  fetchOptions: {\n    requestOptions: {\n      // Use undici's Agent for HTTP/2 support\n      dispatcher: new Agent({\n        allowH2: true,\n        connect: {\n          rejectUnauthorized: false,  // For self-signed certs\n          timeout: 10000\n        }\n      }),\n    // Additional fetch request options\n      headersTimeout: 30000,\n      bodyTimeout: 60000\n    },\n    // Called before making the fetch request\n    onBeforeRequest: async (requestOptions, req, res, options) =\u003e {\n      // Modify outgoing request\n      requestOptions.headers['X-API-Key'] = 'your-api-key';\n      requestOptions.headers['X-Request-ID'] = Math.random().toString(36);\n    },\n    // Called after receiving the fetch response\n    onAfterResponse: async (response, req, res, options) =\u003e {\n      // Access full response object\n      console.log(`Status: ${response.status}`);\n      console.log('Headers:', response.headers);\n      // Note: response.body is a stream that will be piped to res automatically\n    }\n  }\n});\n```\n\n##### HTTP/2 with HTTPS Proxy\n\n```js\nimport { readFileSync } from \"node:fs\";\nimport { Agent } from \"undici\";\n\nconst proxy = createProxyServer({\n  target: \"https://http2-target.example.com\",\n  ssl: {\n    key: readFileSync(\"server-key.pem\"),\n    cert: readFileSync(\"server-cert.pem\")\n  },\n  fetchOptions: {\n    requestOptions: {\n      dispatcher: new Agent({ \n        allowH2: true,\n        connect: { rejectUnauthorized: false }\n      })\n    }\n  },\n}).listen(8443);\n```\n\n\n**Important Notes:**\n- When `fetch` option is provided, the proxy uses the fetch API instead of Node.js native `http`/`https` modules\n- To enable HTTP/2, pass a dispatcher (e.g., from undici with `allowH2: true`) in the fetch configuration\n- The `onBeforeRequest` and `onAfterResponse` callbacks are only available in the fetch code path\n- Traditional `proxyReq` and `proxyRes` events are not emitted in the fetch path - use the callbacks instead\n- The fetch approach is runtime-agnostic and doesn't require undici as a dependency for basic HTTP/1.1 proxying\n\n**[Back to top](#table-of-contents)**\n\n### Options\n\n`httpProxy.createProxyServer` supports the following options:\n\n- **target**: url string to be parsed with the url module\n\n- **forward**: url string to be parsed with the url module or a URL object. A forward proxy without target set just forwards requests but does NOT actually wait for a response and return it to the caller.\n\n- **agent**: object to be passed to http\\(s\\).request \\(see Node's [https agent](http://nodejs.org/api/https.html#https_class_https_agent) and [http agent](http://nodejs.org/api/http.html#http_class_http_agent) objects\\)\n\n- **ssl**: object to be passed to https.createServer\\(\\)\n\n- **ws**: true/false, if you want to proxy websockets\n\n- **xfwd**: true/false, adds x\\-forward headers\n\n- **secure**: true/false, if you want to verify the SSL Certs. Set this to false if you're proxying another server that has a self-signed cert, e.g., [test/examples/http/proxy-https-to-https.test.ts](lib/test/http/proxy-https-to-https.test.ts).\n\n- **toProxy**: true/false, passes the absolute URL as the `path` \\(useful for proxying to proxies\\)\n\n- **prependPath**: true/false, Default: true \\- specify whether you want to prepend the target's path to the proxy path\n\n- **ignorePath**: true/false, Default: false \\- specify whether you want to ignore the proxy path of the incoming request \\(note: you will have to append / manually if required\\).\n\n- **localAddress**: Local interface string to bind for outgoing connections\n\n- **changeOrigin**: true/false, Default: false \\- changes the origin of the host header to the target URL\n\n- **preserveHeaderKeyCase**: true/false, Default: false \\- specify whether you want to keep letter case of response header key\n\n- **auth**: Basic authentication i.e. 'user:password' to compute an Authorization header.\n\n- **hostRewrite**: rewrites the location hostname on \\(201/301/302/307/308\\) redirects.\n\n- **autoRewrite**: rewrites the location host/port on \\(201/301/302/307/308\\) redirects based on requested host/port. Default: false.\n\n- **protocolRewrite**: rewrites the location protocol on \\(201/301/302/307/308\\) redirects to 'http' or 'https'. Default: null.\n\n- **cookieDomainRewrite**: rewrites domain of `set-cookie` headers. Possible values:\n  - `false` \\(default\\): disable cookie rewriting\n  - String: new domain, for example `cookieDomainRewrite: \"new.domain\"`. To remove the domain, use `cookieDomainRewrite: \"\"`.\n  - Object: mapping of domains to new domains, use `\"*\"` to match all domains.\n    For example keep one domain unchanged, rewrite one domain and remove other domains:\n    ```\n    cookieDomainRewrite: {\n      \"unchanged.domain\": \"unchanged.domain\",\n      \"old.domain\": \"new.domain\",\n      \"*\": \"\"\n    }\n    ```\n\n- **cookiePathRewrite**: rewrites path of `set-cookie` headers. Possible values:\n  - `false` \\(default\\): disable cookie rewriting\n  - String: new path, for example `cookiePathRewrite: \"/newPath/\"`. To remove the path, use `cookiePathRewrite: \"\"`. To set path to root use `cookiePathRewrite: \"/\"`.\n  - Object: mapping of paths to new paths, use `\"*\"` to match all paths.\n    For example, to keep one path unchanged, rewrite one path and remove other paths:\n    ```\n    cookiePathRewrite: {\n      \"/unchanged.path/\": \"/unchanged.path/\",\n      \"/old.path/\": \"/new.path/\",\n      \"*\": \"\"\n    }\n    ```\n\n- **headers**: object with extra headers to be added to target requests.\n\n- **proxyTimeout**: timeout \\(in millis\\) for outgoing proxy requests\n\n- **timeout**: timeout \\(in millis\\) for incoming requests\n\n- **followRedirects**: true/false, Default: false \\- specify whether you want to follow redirects\n\n- **selfHandleResponse** true/false, if set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the `proxyRes` event\n\n- **buffer**: stream of data to send as the request body. Maybe you have some middleware that consumes the request stream before proxying it on e.g. If you read the body of a request into a field called 'req.rawbody' you could restream this field in the buffer option:\n\n  ```\n  'use strict';\n\n  const streamify = require('stream-array');\n  const HttpProxy = require('http-proxy');\n  const proxy = new HttpProxy();\n\n  module.exports = (req, res, next) =\u003e {\n\n    proxy.web(req, res, {\n      target: 'http://localhost:4003/',\n      buffer: streamify(req.rawBody)\n    }, next);\n\n  };\n  ```\n\n- **ca**: Optionally override the trusted CA certificates. This is passed to https.request.\n\n- **fetchOptions**: Enable fetch API for HTTP/2 support. Provide an object of type `FetchOptions` for custom configuration:\n  - `requestOptions`: Additional fetch request options (e.g., undici Agent with `allowH2: true` for HTTP/2 as dispatcher)\n  - `onBeforeRequest`: Async callback called before making the fetch request\n  - `onAfterResponse`: Async callback called after receiving the fetch response\n\n**NOTE:**\n`options.ws` and `options.ssl` are optional.\n`options.target` and `options.forward` cannot both be missing\n\nIf you are using the `proxyServer.listen` method, the following options are also applicable:\n\n- **ssl**: object to be passed to https.createServer()\n- **ws**: true/false, if you want to proxy websockets\n\n**[Back to top](#table-of-contents)**\n\n### Configuration Compatibility\n\nThe following table shows which configuration options are compatible with different code paths:\n\n| Option | Native HTTP/HTTPS | Fetch/HTTP/2 | Notes |\n|--------|-------------------|---------------|--------|\n| `target` | ✅ | ✅ | Core option, works in both paths |\n| `forward` | ✅ | ✅ | Core option, works in both paths |\n| `agent` | ✅ | ❌ | Native agents only |\n| `ssl` | ✅ | ✅ | HTTPS server configuration |\n| `ws` | ✅ | ❌ | WebSocket proxying uses native path only |\n| `xfwd` | ✅ | ✅ | X-Forwarded headers |\n| `secure` | ✅ | ❌¹ | SSL certificate verification |\n| `toProxy` | ✅ | ✅ | Proxy-to-proxy configuration |\n| `prependPath` | ✅ | ✅ | Path manipulation |\n| `ignorePath` | ✅ | ✅ | Path manipulation |\n| `localAddress` | ✅ | ✅ | Local interface binding |\n| `changeOrigin` | ✅ | ❌ | Host header rewriting |\n| `preserveHeaderKeyCase` | ✅ | ❌ | Header case preservation |\n| `auth` | ✅ | ✅ | Basic authentication |\n| `hostRewrite` | ✅ | ✅ | Redirect hostname rewriting |\n| `autoRewrite` | ✅ | ✅ | Automatic redirect rewriting |\n| `protocolRewrite` | ✅ | ✅ | Protocol rewriting on redirects |\n| `cookieDomainRewrite` | ✅ | ✅ | Cookie domain rewriting |\n| `cookiePathRewrite` | ✅ | ✅ | Cookie path rewriting |\n| `headers` | ✅ | ✅ | Extra headers to add |\n| `proxyTimeout` | ✅ | ✅ | Outgoing request timeout |\n| `timeout` | ✅ | ✅ | Incoming request timeout |\n| `followRedirects` | ✅ | ✅ | Redirect following |\n| `selfHandleResponse` | ✅ | ✅ | Manual response handling |\n| `buffer` | ✅ | ✅ | Request body stream |\n| `method` | ✅ | ✅ | HTTP method override |\n| `ca` | ✅ | ✅ | Custom CA certificates |\n| `fetch` | ❌ | ✅ | Fetch-specific configuration |\n\n**Notes:**\n- ¹ `secure` is not directly supported in the fetch path. Instead, use a custom dispatcher with `{rejectUnauthorized: false}` to disable SSL certificate verification (e.g., for self-signed certificates).\n\n**Code Path Selection:**\n- **Native Path**: Used by default, supports HTTP/1.1 and WebSockets\n- **Fetch Path**: Activated when `fetchOptions` option is provided, supports HTTP/2 (with appropriate dispatcher)\n\n**Event Compatibility:**\n- **Native Path**: Emits traditional events (`proxyReq`, `proxyRes`, `proxyReqWs`)\n- **Fetch Path**: Uses callback functions (`onBeforeRequest`, `onAfterResponse`) instead of events\n\n**[Back to top](#table-of-contents)**\n\n### Listening for proxy events\n\n- `error`: The error event is emitted if the request to the target fail. **We do not do any error handling of messages passed between client and proxy, and messages passed between proxy and target, so it is recommended that you listen on errors and handle them.**\n- `proxyReq`: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to \"web\" connections\n- `proxyReqWs`: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to \"websocket\" connections\n- `proxyRes`: This event is emitted if the request to the target got a response.\n- `open`: This event is emitted once the proxy websocket was created and piped into the target websocket.\n- `close`: This event is emitted once the proxy websocket was closed.\n- (DEPRECATED) `proxySocket`: Deprecated in favor of `open`.\n\n**Note**: When using the fetch code path (HTTP/2), the `proxyReq` and `proxyRes` events are **not** emitted. Instead, use the `onBeforeRequest` and `onAfterResponse` callback functions in the `fetch` configuration.\n\n#### Traditional Events (Native HTTP/HTTPS path)\n\n```js\nimport { createProxyServer } from \"http-proxy-3\";\n\nconst proxy = createProxyServer({\n  target: \"http://localhost:9005\",\n});\n\nproxy.listen(8005);\n\n// Listen for the `error` event on `proxy`.\nproxy.on(\"error\", (err, req, res) =\u003e {\n  res.writeHead(500, {\n    \"Content-Type\": \"text/plain\",\n  });\n  res.end(\"Something went wrong. And we are reporting a custom error message.\");\n});\n\n// Listen for the `proxyRes` event on `proxy`.\nproxy.on(\"proxyRes\", (proxyRes, req, res) =\u003e {\n  console.log(\n    \"RAW Response from the target\",\n    JSON.stringify(proxyRes.headers, true, 2),\n  );\n});\n\n// Listen for the `open` event on `proxy`.\nproxy.on(\"open\", (proxySocket) =\u003e {\n  // listen for messages coming FROM the target here\n  proxySocket.on(\"data\", hybiParseAndLogMessage);\n});\n```\n\n#### Callback Functions (Fetch/HTTP2 path)\n\n```js\nimport { createProxyServer } from \"http-proxy-3\";\nimport { Agent } from \"undici\";\n\nconst proxy = createProxyServer({\n  target: \"https://api.example.com\",\n  fetchOptions: {\n    requestOptions: {dispatcher: new Agent({ allowH2: true })},\n    // Called before making the fetch request\n    onBeforeRequest: async (requestOptions, req, res, options) =\u003e {\n      // Modify the outgoing request\n      requestOptions.headers['X-Custom-Header'] = 'added-by-callback';\n      console.log('Making request to:', requestOptions.headers.host);\n    },\n    // Called after receiving the fetch response\n    onAfterResponse: async (response, req, res, options) =\u003e {\n      // Access the full response object\n      console.log(`Response: ${response.status}`, response.headers);\n      // Note: response.body is a stream that will be piped to res automatically\n    }\n  }\n});\n```\n\n// Listen for the `close` event on `proxy`.\nproxy.on(\"close\", (res, socket, head) =\u003e {\n  // view disconnected websocket connections\n  console.log(\"Client disconnected\");\n});\n```\n\n**[Back to top](#table-of-contents)**\n\n### Shutdown\n\n- When testing or running server within another program it may be necessary to close the proxy.\n- This will stop the proxy from accepting new connections.\n\n```js\nconst proxy = createProxyServer({\n  target: {\n    host: \"localhost\",\n    port: 1337,\n  },\n});\n\nproxy.close();\n```\n\n**[Back to top](#table-of-contents)**\n\n### Miscellaneous\n\nIf you want to handle your own response after receiving the `proxyRes`, you can do\nso with `selfHandleResponse`. As you can see below, if you use this option, you\nare able to intercept and read the `proxyRes` but you must also make sure to\nreply to the `res` itself otherwise the original client will never receive any\ndata.\n\n### Modify response\n\n```js\nconst option = {\n  target: target,\n  selfHandleResponse: true,\n};\n\nproxy.on(\"proxyRes\", (proxyRes, req, res) =\u003e {\n  var body = [];\n  proxyRes.on(\"data\", (chunk) =\u003e {\n    body.push(chunk);\n  });\n  proxyRes.on(\"end\", () =\u003e {\n    body = Buffer.concat(body).toString();\n    console.log(\"res from proxied server:\", body);\n    res.end(\"my response to cli\");\n  });\n});\n\nproxy.web(req, res, option);\n```\n\n#### ProxyTable API\n\nA proxy table API is available through this add-on [module](https://github.com/donasaur/http-proxy-rules), which lets you define a set of rules to translate matching routes to target routes that the reverse proxy will talk to.\n\n#### **Test**\n\n```sh\npnpm test\n```\n\n**[Back to top](#table-of-contents)**\n\n### Contributing and Issues\n\n- Submit a PR! Port ideas from [https://github.com/http\\-party/node\\-http\\-proxy/pulls](https://github.com/http-party/node-http-proxy/pulls) and [https://github.com/http\\-party/node\\-http\\-proxy/issues](https://github.com/http-party/node-http-proxy/issues). Email me at [wstein@sagemath.com](mailto:wstein@sagemath.com).\n\n**[Back to top](#table-of-contents)**\n\n### License\n\n\u003e The MIT License (MIT)\n\u003e\n\u003e Copyright (c) 2010 - 2025 William Stein, Charlie Robbins, Jarrett Cruger \u0026 all other Contributors.\n\u003e\n\u003e Permission is hereby granted, free of charge, to any person obtaining a copy\n\u003e of this software and associated documentation files (the \"Software\"), to deal\n\u003e in the Software without restriction, including without limitation the rights\n\u003e to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n\u003e copies of the Software, and to permit persons to whom the Software is\n\u003e furnished to do so, subject to the following conditions:\n\u003e\n\u003e The above copyright notice and this permission notice shall be included in\n\u003e all copies or substantial portions of the Software.\n\u003e\n\u003e THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\u003e IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\u003e FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\u003e AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\u003e LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\u003e OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\u003e THE SOFTWARE.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsagemathinc%2Fhttp-proxy-3","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsagemathinc%2Fhttp-proxy-3","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsagemathinc%2Fhttp-proxy-3/lists"}