A Full-Featured HTTP and WebSocket Proxy for Node.js
Proxy Fetch
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.
import { proxyFetch } from "httpxy";// TCP — using a URL stringconst res = await proxyFetch("http://127.0.0.1:3000", "http://example.com/api/data");console.log(await res.json());// Unix socket — using a URL stringconst res2 = await proxyFetch("unix:/tmp/app.sock", "http://localhost/health");console.log(await res2.text());// Or use an object for more controlconst res3 = await proxyFetch({ host: "127.0.0.1", port: 3000 }, "http://example.com/api/data");
It 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.
By 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's FastResponse). The upstream Node.js stream is then passed as the body as-is, skipping the stream conversions:
import { FastResponse } from "srvx";const res = await proxyFetch("http://127.0.0.1:3000", req, undefined, { Response: FastResponse });
Proxy Upgrade
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.
It 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.
If 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.
For 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.
// With optionsserver.on("upgrade", (req, socket, head) => { proxyUpgrade({ host: "127.0.0.1", port: 8080 }, req, socket, head, { // changeOrigin: true, // rewrite Host header // xfwd: false, // disable x-forwarded-* headers (enabled by default) // upgradeTimeout: 5000, // wait up to 5 seconds for upstream response headers });});
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.
On 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.
import { createServer } from "node:http";import { createProxyServer } from "httpxy";const proxy = createProxyServer({});const server = createServer(async (req, res) => { try { await proxy.web(req, res, { target: address /* address of your proxy server here */, }); } catch (error) { console.error(error); res.statusCode = 500; res.end("Proxy error: " + error.toString()); }
Options
Option
Type
Default
Description
target
string | URL | ProxyTargetDetailed
—
Target server URL
forward
string | URL
—
Forward server URL (pipes request without the target's response)
agent
http.Agent | false
keep-alive
Shared keep-alive agent by default. Set false to disable connection reuse
ssl
https.ServerOptions
—
Object passed to https.createServer()
ws
boolean
[!NOTE]
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).
Events
Event
Arguments
Description
error
(err, req, res, target)
An error occurred during proxying
proxyReq
(proxyReq, req, res, options)
Before request is sent to target (modify headers here)
proxyRes
(proxyRes, req, res)
Response received from target
proxyReqWs
(proxyReq, req, socket, options, head)
Before WebSocket upgrade request is sent
open
(proxySocket)
WebSocket connection opened
close
(proxyRes, proxySocket, proxyHead)
WebSocket connection closed
Examples
HTTP Proxy
import { createServer } from "node:http";import { createProxyServer } from "httpxy";const proxy = createProxyServer({});const server = createServer(async (req, res) => { await proxy.web(req, res, { target: "http://localhost:8080" });});server.listen(3000);