{"name":"httpxy","version":"0.2.2","license":"MIT","_id":"httpxy@0.2.2","maintainers":[{"name":"pi0","email":"pyapar@gmail.com"}],"homepage":"https://github.com/unjs/httpxy#readme","bugs":{"url":"https://github.com/unjs/httpxy/issues"},"dist":{"shasum":"1603165cfd12087f2039c4a8532ce61eab5d84e5","tarball":"http://registry-npm.ywwl.com/httpxy/download/httpxy-0.2.2.tgz","fileCount":8,"integrity":"sha512-QnS6mAOqvdmfctFaD/Kp5cwRMcaUhEmIyw2rjVYnhJb8EuAyd/79biT/50HUTKvq/PwoXYTP6J3d9TUxzHFZwA==","signatures":[{"sig":"MEYCIQDyeNwPrT1OTjr+Yc+hQkzYVT4DLYqVPQmhBjgWpGGUIQIhAJFUYy4VbeOmRyVBjhi9EiUjUOv0hQTy4tG2cfdL4j3G","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":61730,"size":9433,"noattachment":false,"key":"/httpxy/-/httpxy-0.2.2.tgz"},"main":"./dist/index.cjs","type":"module","types":"./dist/index.d.ts","module":"./dist/index.mjs","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.mjs","require":"./dist/index.cjs"}},"gitHead":"32d2f0ec36d8231d28a42c8a6c76de9cc9e4347d","scripts":{"dev":"vitest","lint":"oxlint . && oxfmt --check src test","play":"jiti ./playground","test":"pnpm lint && pnpm test:types && vitest run --coverage","build":"unbuild","prepack":"pnpm run build","release":"pnpm test && pnpm build && changelogen --release && npm publish && git push --follow-tags","lint:fix":"oxlint . --fix && oxfmt src test","test:types":"tsgo --noEmit"},"_npmUser":{"name":"pi0","email":"pyapar@gmail.com"},"repository":{"url":"git+https://github.com/unjs/httpxy.git","type":"git"},"_npmVersion":"11.6.1","description":"A full-featured HTTP proxy for Node.js.","directories":{},"sideEffects":false,"_nodeVersion":"24.10.0","_hasShrinkwrap":false,"packageManager":"pnpm@10.29.2","devDependencies":{"ws":"^8.19.0","sse":"^0.0.8","jiti":"^2.6.1","async":"^3.2.6","oxfmt":"^0.31.0","ofetch":"^1.5.1","oxlint":"^1.46.0","semver":"^7.7.4","vitest":"^4.0.18","listhen":"^1.9.0","unbuild":"^3.6.1","@types/ws":"^8.18.1","expect.js":"^0.3.1","socket.io":"^4.8.3","@types/sse":"^0.0.0","typescript":"^5.9.3","@types/node":"^25.2.3","changelogen":"^0.6.2","@types/async":"^3.2.25","concat-stream":"^2.0.0","@types/express":"^5.0.6","socket.io-client":"^4.8.3","eslint-config-unjs":"^0.6.2","@vitest/coverage-v8":"^4.0.18","@types/concat-stream":"^2.0.3","@typescript/native-preview":"^7.0.0-dev.20260210.1"},"_npmOperationalInternal":{"tmp":"tmp/httpxy_0.2.2_1770830591151_0.24191515993676682","host":"s3://npm-registry-packages-npm-production"},"readme":"# 🔀 httpxy\n\n[![npm version][npm-version-src]][npm-version-href]\n[![npm downloads][npm-downloads-src]][npm-downloads-href]\n[![bundle][bundle-src]][bundle-href]\n[![Codecov][codecov-src]][codecov-href]\n\nA Full-Featured HTTP and WebSocket Proxy for Node.js\n\n## Proxy Fetch\n\n`proxyFetch` is a proxy utility with web standard (`Request`/`Response`) interfaces. It forwards requests to a specific server address (TCP host/port or Unix socket), bypassing the URL's hostname.\n\n```ts\nimport { proxyFetch } from \"httpxy\";\n\n// TCP — using a URL string\nconst res = await proxyFetch(\"http://127.0.0.1:3000\", \"http://example.com/api/data\");\nconsole.log(await res.json());\n\n// Unix socket — using a URL string\nconst res2 = await proxyFetch(\"unix:/tmp/app.sock\", \"http://localhost/health\");\nconsole.log(await res2.text());\n\n// Or use an object for more control\nconst res3 = await proxyFetch({ host: \"127.0.0.1\", port: 3000 }, \"http://example.com/api/data\");\n\n// Using a Request object\nconst req = new Request(\"http://example.com/api/data\", {\n  method: \"POST\",\n  headers: { \"Content-Type\": \"application/json\" },\n  body: JSON.stringify({ key: \"value\" }),\n});\nconst res4 = await proxyFetch(\"http://127.0.0.1:3000\", req);\n\n// Using a URL string with RequestInit\nconst res5 = await proxyFetch(\"http://127.0.0.1:3000\", \"http://example.com/api/data\", {\n  method: \"PUT\",\n  headers: { Authorization: \"Bearer token\" },\n  body: JSON.stringify({ updated: true }),\n});\n```\n\nIt accepts the same `input` and `init` arguments as the global `fetch`, including `Request` objects and streaming bodies, and returns a standard `Response`. Redirects are handled manually by default.\n\nBy default, the upstream body is converted to a web `ReadableStream`. When the response is served by a Node.js server, you can pass a custom `Response` constructor that accepts Node.js streams (such as [srvx](https://srvx.h3.dev)'s `FastResponse`). The upstream Node.js stream is then passed as the body as-is, skipping the stream conversions:\n\n```ts\nimport { FastResponse } from \"srvx\";\n\nconst res = await proxyFetch(\"http://127.0.0.1:3000\", req, undefined, { Response: FastResponse });\n```\n\n## Proxy Upgrade\n\n`proxyUpgrade` is a standalone WebSocket upgrade proxy. It forwards `upgrade` requests to a target server without needing a `ProxyServer` instance — the WebSocket counterpart to `proxyFetch`.\n\n```ts\nimport { createServer } from \"node:http\";\nimport { proxyUpgrade } from \"httpxy\";\n\nconst server = createServer((req, res) => {\n  // Handle regular HTTP requests...\n});\n\nserver.on(\"upgrade\", (req, socket, head) => {\n  proxyUpgrade(\"http://127.0.0.1:8080\", req, socket, head);\n});\n\nserver.listen(3000);\n```\n\nIt accepts the same `addr` formats as `proxyFetch` (`\"http://host:port\"`, `\"unix:/path\"`, or `{ host, port }` / `{ socketPath }`), and returns a `Promise<Socket>` that resolves with the upstream proxy socket once the WebSocket connection is established.\n\nIf the upstream responds without upgrading (e.g. `401` or `404`), both `proxyUpgrade` and `ProxyServer.ws` stream the status, headers, and body to the client with `Connection: close` and valid framing (chunked bodies are re-encoded, hop-by-hop headers including `Upgrade` are stripped, nothing is buffered). `proxyUpgrade` rejects as soon as the response headers arrive while the body may still be streaming, so avoid destroying the client socket in that rejection handler. If the upstream fails mid-body after that point, the client socket is destroyed so the client sees a truncated response; the already-rejected promise does not report it.\n\nFor bodyless responses, `Content-Length` is removed from `204` responses and preserved as representation metadata on `304` responses. A `205` response is sent with `Content-Length: 0` and no transfer encoding; any upstream body is canceled instead of forwarded.\n\n```ts\n// With options\nserver.on(\"upgrade\", (req, socket, head) => {\n  proxyUpgrade({ host: \"127.0.0.1\", port: 8080 }, req, socket, head, {\n    // changeOrigin: true, // rewrite Host header\n    // xfwd: false, // disable x-forwarded-* headers (enabled by default)\n    // upgradeTimeout: 5000, // wait up to 5 seconds for upstream response headers\n  });\n});\n```\n\n`upgradeTimeout` (also available on `ProxyServer`) is an optional deadline in milliseconds, including connection setup, for the upstream upgrade or a final response's headers. Informational responses and partial headers do not extend it, and it never limits an established WebSocket or a non-upgrade response body. Omitted, non-positive, and non-finite values disable it; values above `2147483647` are capped.\n\nOn expiry, the upstream request and client socket are destroyed (no HTTP 504 is written) and an error with `code: \"ERR_UPSTREAM_UPGRADE_TIMEOUT\"` and `statusCode: 504` is reported. While the deadline is active, a client disconnect also cancels the pending upstream request and is reported as an `ECONNRESET` error.\n\n## Proxy Server\n\n> [!NOTE]\n> Proxy server was originally forked from [http-party/node-http-proxy](https://github.com/http-party/node-http-proxy).\n\nCreate proxy:\n\n```ts\nimport { createServer } from \"node:http\";\nimport { createProxyServer } from \"httpxy\";\n\nconst proxy = createProxyServer({});\n\nconst server = createServer(async (req, res) => {\n  try {\n    await proxy.web(req, res, {\n      target: address /* address of your proxy server here */,\n    });\n  } catch (error) {\n    console.error(error);\n    res.statusCode = 500;\n    res.end(\"Proxy error: \" + error.toString());\n  }\n});\n\nserver.listen(3000, () => {\n  console.log(\"Proxy is listening on http://localhost:3000\");\n});\n```\n\n## Options\n\n| Option                  | Type                                   | Default    | Description                                                                 |\n| ----------------------- | -------------------------------------- | ---------- | --------------------------------------------------------------------------- |\n| `target`                | `string \\| URL \\| ProxyTargetDetailed` | —          | Target server URL                                                           |\n| `forward`               | `string \\| URL`                        | —          | Forward server URL (pipes request without the target's response)            |\n| `agent`                 | `http.Agent \\| false`                  | keep-alive | Shared keep-alive agent by default. Set `false` to disable connection reuse |\n| `ssl`                   | `https.ServerOptions`                  | —          | Object passed to `https.createServer()`                                     |\n| `ws`                    | `boolean`                              | `false`    | Enable WebSocket proxying                                                   |\n| `xfwd`                  | `boolean`                              | `false`    | Add `x-forwarded-*` headers                                                 |\n| `secure`                | `boolean`                              | —          | Verify SSL certificates                                                     |\n| `toProxy`               | `boolean`                              | `false`    | Pass absolute URL as path (proxy-to-proxy)                                  |\n| `prependPath`           | `boolean`                              | `true`     | Prepend the target's path to the proxy path                                 |\n| `ignorePath`            | `boolean`                              | `false`    | Ignore the incoming request path                                            |\n| `localAddress`          | `string`                               | —          | Local interface to bind for outgoing connections                            |\n| `changeOrigin`          | `boolean`                              | `false`    | Change the `Host` header to match the target URL                            |\n| `preserveHeaderKeyCase` | `boolean`                              | `false`    | Keep original letter case of response header keys                           |\n| `auth`                  | `string`                               | —          | Basic authentication (`'user:password'`) for `Authorization` header         |\n| `hostRewrite`           | `string`                               | —          | Rewrite the `Location` hostname on redirects (301/302/307/308)              |\n| `autoRewrite`           | `boolean`                              | `false`    | Rewrite `Location` host/port on redirects based on the request              |\n| `protocolRewrite`       | `string`                               | —          | Rewrite `Location` protocol on redirects (`'http'` or `'https'`)            |\n| `cookieDomainRewrite`   | `false \\| string \\| object`            | `false`    | Rewrite domain of `Set-Cookie` headers                                      |\n| `cookiePathRewrite`     | `false \\| string \\| object`            | `false`    | Rewrite path of `Set-Cookie` headers                                        |\n| `headers`               | `object`                               | —          | Extra headers to add to target requests                                     |\n| `proxyTimeout`          | `number`                               | `120000`   | Timeout (ms) for the proxy request to the target                            |\n| `upgradeTimeout`        | `number`                               | —          | Deadline (ms) for a WebSocket upgrade response; see Proxy Upgrade           |\n| `timeout`               | `number`                               | —          | Timeout (ms) for the incoming request                                       |\n| `selfHandleResponse`    | `boolean`                              | `false`    | Disable automatic response piping (handle `proxyRes` yourself)              |\n| `followRedirects`       | `boolean \\| number`                    | `false`    | Follow HTTP redirects from target. `true` = max 5 hops; number = custom max |\n| `buffer`                | `stream.Stream`                        | —          | Stream to use as request body instead of the incoming request               |\n\n> [!NOTE]\n> Redirect rewriting (`hostRewrite`, `autoRewrite`, `protocolRewrite`) only applies when the `Location` header host matches the target host, so cross-origin redirects are never altered. A protocol-relative `Location` (`//host/path`) is kept protocol-relative when only the host is rewritten (`hostRewrite`/`autoRewrite`), so the client resolves the scheme itself. Setting `protocolRewrite` explicitly opts into a concrete scheme and absolutizes such values (e.g. `//host/path` → `https://host/path`).\n\n## Events\n\n| Event        | Arguments                                | Description                                            |\n| ------------ | ---------------------------------------- | ------------------------------------------------------ |\n| `error`      | `(err, req, res, target)`                | An error occurred during proxying                      |\n| `proxyReq`   | `(proxyReq, req, res, options)`          | Before request is sent to target (modify headers here) |\n| `proxyRes`   | `(proxyRes, req, res)`                   | Response received from target                          |\n| `proxyReqWs` | `(proxyReq, req, socket, options, head)` | Before WebSocket upgrade request is sent               |\n| `open`       | `(proxySocket)`                          | WebSocket connection opened                            |\n| `close`      | `(proxyRes, proxySocket, proxyHead)`     | WebSocket connection closed                            |\n| `start`      | `(req, res, target)`                     | Proxy processing started                               |\n| `end`        | `(req, res, proxyRes)`                   | Proxy request completed                                |\n\n## Examples\n\n### HTTP Proxy\n\n```ts\nimport { createServer } from \"node:http\";\nimport { createProxyServer } from \"httpxy\";\n\nconst proxy = createProxyServer({});\n\nconst server = createServer(async (req, res) => {\n  await proxy.web(req, res, { target: \"http://localhost:8080\" });\n});\n\nserver.listen(3000);\n```\n\n### WebSocket Proxy\n\n```ts\nimport { createServer } from \"node:http\";\nimport { createProxyServer } from \"httpxy\";\n\nconst proxy = createProxyServer({ target: \"http://localhost:8080\", ws: true });\n\nconst server = createServer(async (req, res) => {\n  await proxy.web(req, res);\n});\n\nserver.on(\"upgrade\", (req, socket, head) => {\n  proxy.ws(req, socket, { target: \"http://localhost:8080\" }, head);\n});\n\nserver.listen(3000);\n```\n\n### Modify Request Headers\n\n```ts\nimport { createServer } from \"node:http\";\nimport { createProxyServer } from \"httpxy\";\n\nconst proxy = createProxyServer({ target: \"http://localhost:8080\" });\n\nproxy.on(\"proxyReq\", (proxyReq) => {\n  proxyReq.setHeader(\"X-Forwarded-By\", \"httpxy\");\n});\n\nconst server = createServer(async (req, res) => {\n  await proxy.web(req, res);\n});\n\nserver.listen(3000);\n```\n\n### HTTPS Proxy\n\n```ts\nimport { readFileSync } from \"node:fs\";\nimport { createProxyServer } from \"httpxy\";\n\nconst proxy = createProxyServer({\n  ssl: {\n    key: readFileSync(\"server-key.pem\", \"utf8\"),\n    cert: readFileSync(\"server-cert.pem\", \"utf8\"),\n  },\n  target: \"https://localhost:8443\",\n  secure: false, // allow self-signed certificates\n});\n\nproxy.listen(3000);\n```\n\n### Standalone Proxy Server\n\n```ts\nimport { createProxyServer } from \"httpxy\";\n\nconst proxy = createProxyServer({\n  target: \"http://localhost:8080\",\n  changeOrigin: true,\n});\n\nproxy.listen(3000);\n```\n\n## Development\n\n- Clone this repository\n- Install latest LTS version of [Node.js](https://nodejs.org/en/)\n- Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable`\n- Install dependencies using `pnpm install`\n- Run interactive tests using `pnpm dev`\n\n## Acknowledgements\n\nPerformance optimizations in httpxy were inspired by analysis of [fast-proxy](https://github.com/fastify/fast-proxy) and [@fastify/http-proxy](https://github.com/fastify/fastify-http-proxy).\n\n## License\n\nMade with 💛\n\nPublished under [MIT License](./LICENSE).\n\n<!-- Badges -->\n\n[npm-version-src]: https://img.shields.io/npm/v/httpxy?style=flat&colorA=18181B&colorB=F0DB4F\n[npm-version-href]: https://npmjs.com/package/httpxy\n[npm-downloads-src]: https://img.shields.io/npm/dm/httpxy?style=flat&colorA=18181B&colorB=F0DB4F\n[npm-downloads-href]: https://npmjs.com/package/httpxy\n[codecov-src]: https://img.shields.io/codecov/c/gh/unjs/httpxy/main?style=flat&colorA=18181B&colorB=F0DB4F\n[codecov-href]: https://codecov.io/gh/unjs/httpxy\n[bundle-src]: https://img.shields.io/bundlephobia/minzip/httpxy?style=flat&colorA=18181B&colorB=F0DB4F\n[bundle-href]: https://bundlephobia.com/result?p=httpxy\n","publish_time":1770830591308,"_cnpm_publish_time":1770830591308,"dist-tags":{"latest":"0.5.6"}}