How to Proxy HTTP Requests in Node.js
Write a reverse proxy with node:http that streams bodies to an upstream, strips hop-by-hop headers, adds X-Forwarded-For and returns 502 on failure.

A proxy sits between a client and another server and passes requests along. You may want one to forward /api to a backend during development, to hide an upstream behind your own domain, to add authentication or logging in one place, or to avoid a browser CORS restriction by making the request from the server. Node.js can do this with node:http alone, and writing a small one is the best way to understand what proxy libraries handle for you. This post builds a reverse proxy that streams request and response bodies, removes headers that must not be forwarded, adds the standard forwarding headers, answers 502 when the upstream fails, and discusses what to leave to a mature tool. The samples use Node.js 26 and the http.request documentation.
The idea
A reverse proxy does four things for every request: accept it from the client, open a request to the upstream with the same method, path and headers, copy the client's body to the upstream, and copy the upstream's status, headers and body back to the client. Because both ends are streams, it can do this without holding a whole body in memory.
client -> proxy (:3000) -> upstream (:4000)
client <- proxy <- upstreamFor the samples, assume a simple upstream is already running on port 4000 and answers GET /hello with the text hello from upstream.
The smallest proxy
http.request creates an outgoing request. The incoming request is a readable stream, so pipe copies its body to the upstream, and the upstream response is a readable stream that copies back to the client.
import { createServer, request } from "node:http";
const UPSTREAM = { host: "127.0.0.1", port: 4000 };
createServer((clientReq, clientRes) => {
const upstreamReq = request(
{
...UPSTREAM,
method: clientReq.method,
path: clientReq.url,
headers: clientReq.headers,
},
(upstreamRes) => {
clientRes.writeHead(upstreamRes.statusCode, upstreamRes.headers);
upstreamRes.pipe(clientRes);
},
);
clientReq.pipe(upstreamReq);
}).listen(3000, () => console.log("proxy on :3000"));proxy on :3000curl -s localhost:3000/hellohello from upstreamThis works for a first test, and it has several problems that real traffic exposes. The next sections fix them in order.
Headers that must not be forwarded
HTTP defines hop-by-hop headers that apply to one connection and must not pass through a proxy. They are Connection, Keep-Alive, Proxy-Authenticate, Proxy-Authorization, TE, Trailer, Transfer-Encoding and Upgrade, as well as any header named in the Connection header, as set out in RFC 9110 section 7.6.1. Forwarding them can break framing between the two connections.
const HOP_BY_HOP = new Set([
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailer",
"transfer-encoding",
"upgrade",
]);
export function forwardHeaders(headers) {
const named = String(headers.connection ?? "")
.split(",")
.map((s) => s.trim().toLowerCase())
.filter(Boolean);
const out = {};
for (const [name, value] of Object.entries(headers)) {
if (HOP_BY_HOP.has(name) || named.includes(name)) continue;
out[name] = value;
}
return out;
}
console.log(forwardHeaders({ host: "a.test", connection: "close, x-trace", "x-trace": "1", accept: "*/*" }));{ host: 'a.test', accept: '*/*' }Node.js lower-cases incoming header names, so the comparison is on lower-case names. The sample removes connection and also x-trace because the connection header named it.
Host, forwarding headers and the client address
The Host header normally should name the upstream, because many servers use it to choose a site. Set it to the upstream's host. Then tell the upstream about the original client with the de facto X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Host headers, or the standard Forwarded header from RFC 7239.
export function addForwarded(headers, clientReq, upstreamHost) {
const ip = clientReq.socket.remoteAddress ?? "";
const prior = headers["x-forwarded-for"];
return {
...headers,
host: upstreamHost,
"x-forwarded-for": prior ? `${prior}, ${ip}` : ip,
"x-forwarded-host": clientReq.headers.host ?? "",
"x-forwarded-proto": "http",
};
}For a client at 203.0.113.7 calling proxy.test:3000, the upstream receives:
host: 127.0.0.1:4000
x-forwarded-for: 203.0.113.7
x-forwarded-host: proxy.test:3000
x-forwarded-proto: httpAppend to an existing X-Forwarded-For rather than replacing it, so a chain of proxies keeps its history. Be aware that a client can send a forged value, so the upstream should trust that header only from proxies it knows.
The complete proxy
Put the pieces together and add the failure handling. A proxy has two failure points: the upstream may be unreachable or reset mid-response, and the client may disconnect while the upstream is still working.
import { createServer, request } from "node:http";
import { pipeline } from "node:stream";
import { forwardHeaders } from "./hop-by-hop.js";
import { addForwarded } from "./forwarded.js";
const UPSTREAM = { host: "127.0.0.1", port: 4000 };
const server = createServer((clientReq, clientRes) => {
const headers = addForwarded(forwardHeaders(clientReq.headers), clientReq, `${UPSTREAM.host}:${UPSTREAM.port}`);
const upstreamReq = request(
{ ...UPSTREAM, method: clientReq.method, path: clientReq.url, headers, timeout: 10_000 },
(upstreamRes) => {
clientRes.writeHead(upstreamRes.statusCode, forwardHeaders(upstreamRes.headers));
pipeline(upstreamRes, clientRes, () => {});
},
);
upstreamReq.on("timeout", () => upstreamReq.destroy(new Error("upstream timeout")));
upstreamReq.on("error", (err) => {
if (clientRes.headersSent) {
clientRes.destroy();
return;
}
const status = err.message === "upstream timeout" ? 504 : 502;
clientRes.writeHead(status, { "content-type": "text/plain" });
clientRes.end(status === 504 ? "gateway timeout" : "bad gateway");
});
pipeline(clientReq, upstreamReq, () => {});
});
server.listen(3000, () => console.log("proxy on :3000"));proxy on :3000Test the three outcomes.
curl -s -i localhost:3000/hello | head -1
curl -s -i localhost:3000/hello | tail -1With the upstream running:
HTTP/1.1 200 OK
hello from upstreamStop the upstream and request again:
curl -s -i localhost:3000/hello | sed -n '1p;$p'HTTP/1.1 502 Bad Gateway
bad gatewayThe status codes are the proxy's vocabulary. 502 Bad Gateway means the proxy got an invalid response or none, and 504 Gateway Timeout means the upstream was too slow. Using them tells operators the problem is behind the proxy, not in it. The pipeline calls forward errors and destroy both sides when one fails, which prevents a stuck connection when the client closes early.
Rewriting paths
A common need is to mount the upstream under a prefix, so /api/users becomes /users upstream.
export function rewritePath(url, prefix = "/api") {
return url.startsWith(prefix) ? url.slice(prefix.length) || "/" : url;
}
console.log(rewritePath("/api/users?limit=5"));
console.log(rewritePath("/api"));
console.log(rewritePath("/other"));/users?limit=5
/
/otherApply it to path when you build the upstream request and send everything else to a different upstream or a 404.
Proxying WebSockets
An upgrade request does not go through the normal request listener. The server emits an upgrade event instead, and a proxy must connect to the upstream and pipe the raw sockets together. That is a separate piece of code with its own header rules, and it is a good moment to use a library.
server.on("upgrade", (req, socket, head) => {
console.log("upgrade requested for", req.url);
socket.destroy();
});upgrade requested for /socketThe sample refuses the upgrade by closing the socket, which is better than letting it hang.
Fetch-based forwarding
For a small JSON gateway you can skip the stream plumbing and use fetch to call the upstream, then relay the result. That buffers the body, so it suits small payloads, and it gives you the response as an object you can inspect or modify.
const upstream = await fetch("http://127.0.0.1:4000/hello");
const body = await upstream.text();
console.log(upstream.status, body);200 hello from upstreamfetch also decodes compressed bodies, so if you relay the response you must drop the content-encoding and content-length headers of the original, or the client will see a length that no longer matches.
When to use a library or a real proxy
The proxy above handles the common path, and it is a good teaching tool and a fine development helper. Production proxying involves much more: upgrade handling, connection pooling and keep-alive tuning, TLS to the upstream, health checks, load balancing, buffering limits and careful header policy. Packages such as http-proxy and http-proxy-middleware cover many of these, and nginx, HAProxy or a cloud load balancer do the job with far less code on your side. Write your own when the logic is the point, such as authentication or request rewriting, and let a dedicated tool carry the traffic.
Security questions to ask
A proxy forwards traffic on your behalf, which makes it a security boundary. The most important rule is to never let the client choose the upstream. If the target host comes from a query parameter or a header, you have built an open proxy, and attackers can use it to reach internal services, cloud metadata addresses or other hosts through your network, a class of problem known as server-side request forgery. Keep the upstream fixed in configuration, or choose it from a short allow list.
Limit what passes through. Decide which paths and methods the proxy exposes, strip headers that carry credentials meant for the proxy and not for the upstream, and set a maximum body size. Log the upstream status and the time taken, so that you can see when a backend is slow. If the proxy adds an identity header for the upstream, such as a user id after authentication, remove any copy of that header that arrived from the client, otherwise a caller can impersonate someone by sending it themselves.
Testing a proxy
Start two servers in a test: a fake upstream that records what it receives and returns a known body, and the proxy pointed at it, both on port 0. Send requests with fetch and assert on the status, the body, the forwarded headers the upstream saw and the behaviour when the upstream is stopped. Those few cases cover the contract: requests arrive intact, hop-by-hop headers are gone, forwarding headers are present, and failures become 502 or 504.


