Node.js Proxy Setup: fetch, undici, got and SOCKS5

Route Node.js through a proxy: NODE_USE_ENV_PROXY, undici ProxyAgent for fetch, got, node-fetch, http and https agents, SOCKS5, rotation and error fixes.

Current Node.js releases can send fetch, http and https requests through a proxy with no packages and no code changes. Set the proxy variables and opt in with NODE_USE_ENV_PROXY=1:

export NODE_USE_ENV_PROXY=1
export HTTP_PROXY="http://USERNAME:PASSWORD@HOST:PORT"
export HTTPS_PROXY="http://USERNAME:PASSWORD@HOST:PORT"
node app.mjs
// app.mjs
const res = await fetch("https://api.ipify.org");
console.log(res.status, await res.text());

It prints 200 and the proxy's exit address. Without the opt-in variable, Node ignores HTTP_PROXY and HTTPS_PROXY and the same script prints your own address.

To set the proxy in code instead, give fetch a dispatcher from the undici package:

import { fetch, ProxyAgent } from "undici";

const dispatcher = new ProxyAgent("http://USERNAME:PASSWORD@HOST:PORT");

const res = await fetch("https://api.ipify.org", { dispatcher });
console.log(res.status, await res.text());

await dispatcher.close();

What you need: Node.js 22.21 or later (24.5 or later on the 24 line) for the environment switch, npm install undici for the second example, and a proxy URL. The samples use import and top-level await, so save them as .mjs files or set "type": "module" in package.json. On Node4, copy the URL from the Connect card on the dashboard's Proxies page. A free account runs every HTTP example here, with 3 shared datacenter proxies and 1 GB of traffic a month. SOCKS5 and the rotating gateways need a paid plan. Everything on this page was run on Node 24.14 with undici 8.12, got 16.2, node-fetch 3.3, https-proxy-agent 9.1 and socks-proxy-agent 10.1.

Each Node client takes its proxy a different way. Find yours:

ClientHow to set a proxyReads HTTP_PROXY on its own?
Built-in fetchNODE_USE_ENV_PROXY=1, or an undici dispatcherOnly with the opt-in
undici from npmProxyAgent or EnvHttpProxyAgentOnly through EnvHttpProxyAgent
http and https modulesAn agent, or the opt-inOnly with the opt-in
gotagent: { http, https }No. It follows the opt-in, because it runs on http and https
node-fetchagentNo. Same as got
axiosIts proxy option or agents: see the axios proxy guideYes, by default

Every example reaches an https:// target through a proxy URL that starts with http://. That is the normal arrangement: the hop to the proxy is plain HTTP, the client asks for a CONNECT tunnel, and TLS runs end to end with the destination inside it. Headless browsers are a separate topic, covered in Puppeteer and Playwright proxies, and the Python equivalent of this page is Python requests proxy setup.

Node.js fetch through a proxy

Node's fetch has no proxy option, and it ignores the agent option that older HTTP clients use. Passing { agent: new HttpsProxyAgent(...) } to the built-in fetch raised no error in our test and fetched the page directly from our own address. There are two supported routes: the runtime's environment switch, and an undici dispatcher.

Option 1: NODE_USE_ENV_PROXY and --use-env-proxy

The opt-in is a variable (NODE_USE_ENV_PROXY=1) or a flag (node --use-env-proxy app.mjs). Either makes Node read HTTP_PROXY, HTTPS_PROXY and NO_PROXY at startup and apply them to fetch and to the default http and https agents. The Node documentation marks the feature as under active development, and it arrived in steps:

CapabilityAdded in
NODE_USE_ENV_PROXY=1, applied to fetchNode 24.0.0 and 22.21.0
--use-env-proxy, http and https support, the proxyEnv agent optionNode 24.5.0 and 22.21.0
http.setGlobalProxyFromEnv()Node 25.4.0 and 24.14.0

What the switch did on Node 24.14, measured against a logging proxy:

  • Credentials in the URL work, for fetch, https.get and http.get.
  • Set both variables. With only HTTP_PROXY set, fetch used it for https:// URLs too, but https.get went direct. One process, two different exits.
  • ALL_PROXY is not read. With only ALL_PROXY set, every request went direct.
  • NO_PROXY takes a comma-separated list: exact hosts, .example.com suffixes, *.example.com wildcards, IP addresses and ranges. * bypasses the proxy for everything.
  • A SOCKS URL is not accepted. HTTPS_PROXY=socks5://... stopped the process at startup with Invalid URL protocol.
  • Requests reuse tunnels. Three https.get calls to one host shared a single CONNECT.

From Node 24.14 the same switch is available at runtime, which helps when the proxy URL comes from your own config instead of the shell:

import http from "node:http";

const proxyUrl = "http://USERNAME:PASSWORD@HOST:PORT";

const restore = http.setGlobalProxyFromEnv({
  http_proxy: proxyUrl,
  https_proxy: proxyUrl,
  no_proxy: "localhost,127.0.0.1",
});

const res = await fetch("https://api.ipify.org");
console.log(res.status, await res.text());

restore(); // back to direct connections

Call it before the first request. It replaces the global agents and the global fetch dispatcher, and the function it returns puts the previous ones back.

One trap applies to the whole option. Loading the undici npm package replaces the global dispatcher that the built-in fetch uses. On Node 24.14 with NODE_USE_ENV_PROXY=1, the built-in fetch was proxied until the script ran import "undici" (version 8.12), and went direct afterwards, with no error. A dependency can do that import for you. If the package is in your tree, set the dispatcher yourself, as below, and do not rely on the switch for fetch.

Option 2: undici ProxyAgent

Node's fetch is undici underneath, and undici takes a proxy through a dispatcher. Two rules keep it working:

Use fetch and ProxyAgent from the same copy of undici. Node bundles its own undici (process.versions.undici prints the version), and the npm package is usually a different major. Node 24.14 bundles undici 7. Passing a ProxyAgent from undici 8 to the built-in fetch as { dispatcher } failed with fetch failed, caused by invalid onRequestStart method, before anything reached the proxy. Importing fetch from undici, as the example at the top does, avoids the mismatch.

To proxy every fetch in the process, set the global dispatcher. This form did work across the two copies: the built-in fetch on Node 24.14 honored a global dispatcher set through undici 8.

import { ProxyAgent, setGlobalDispatcher } from "undici";

setGlobalDispatcher(new ProxyAgent("http://USERNAME:PASSWORD@HOST:PORT"));

// The built-in fetch, with no dispatcher argument, now goes through the proxy.
const res = await fetch("https://api.ipify.org");
console.log(res.status, await res.text());

dispatcher is undici's extension, not part of the fetch standard, so TypeScript's DOM types reject it on the global fetch. The fetch exported by undici carries the right types. undici 8 needs Node 22.19 or later.

For the environment variables without the runtime switch, undici has EnvHttpProxyAgent. It reads HTTP_PROXY, HTTPS_PROXY and NO_PROXY (lowercase names win when both are set), or takes them as options:

import { EnvHttpProxyAgent, fetch } from "undici";

const proxyUrl = "http://USERNAME:PASSWORD@HOST:PORT";

// With no options it reads the environment. Options override it.
const dispatcher = new EnvHttpProxyAgent({
  httpProxy: proxyUrl,
  httpsProxy: proxyUrl,
  noProxy: "localhost,127.0.0.1",
});

const res = await fetch("https://api.ipify.org", { dispatcher });
console.log(res.status, await res.text());

await dispatcher.close();

undici.request and pool size

undici.request is the lower-level API under fetch, and it takes the same dispatcher. ProxyAgent accepts undici's pool options, and connections caps how many tunnels it opens per destination:

import { ProxyAgent, request } from "undici";

const dispatcher = new ProxyAgent({
  uri: "http://USERNAME:PASSWORD@HOST:PORT",
  connections: 5,
});

const { statusCode, body } = await request("https://api.ipify.org", { dispatcher });
console.log(statusCode, await body.text());

await dispatcher.close();

With connections: 2, six parallel requests to one host ran through two tunnels in our test. Create one dispatcher at module scope and share it. A dispatcher per request discards the pool and pays for a new connection, a new tunnel and a new TLS handshake every time.

got proxy

got has no proxy option and reads no environment variables. It takes agents, one per target scheme:

npm install got https-proxy-agent http-proxy-agent
import got from "got";
import { HttpProxyAgent } from "http-proxy-agent";
import { HttpsProxyAgent } from "https-proxy-agent";

const proxyUrl = "http://USERNAME:PASSWORD@HOST:PORT";

const client = got.extend({
  agent: {
    http: new HttpProxyAgent(proxyUrl, { keepAlive: true }),
    https: new HttpsProxyAgent(proxyUrl, { keepAlive: true }),
  },
  timeout: { request: 30_000 },
  retry: { limit: 2 },
});

console.log(await client("https://api.ipify.org").text());

got 16 needs Node 22 or later and is an ES module. Two behaviors to know behind a proxy:

  • A refused tunnel is an HTTPError. A 407 from the proxy rejects with "Request failed with status code 407 (Proxy Authentication Required)".
  • got retries 429 by default. A Rotating Unmetered plan at its connection limit answers 429 at the proxy, and got with retry.limit: 2 knocked three times in a row. Those retries cannot succeed until a connection closes, so cap the limit and keep your concurrency under the plan. Connection limits has the details.

node-fetch proxy

node-fetch takes an agent, either one agent or a function that picks by URL. Use the function, so http:// URLs and redirects to them stay on the proxy:

import fetch from "node-fetch";
import { HttpProxyAgent } from "http-proxy-agent";
import { HttpsProxyAgent } from "https-proxy-agent";

const proxyUrl = "http://USERNAME:PASSWORD@HOST:PORT";
const httpAgent = new HttpProxyAgent(proxyUrl);
const httpsAgent = new HttpsProxyAgent(proxyUrl);

const res = await fetch("https://api.ipify.org", {
  agent: (url) => (url.protocol === "http:" ? httpAgent : httpsAgent),
});
console.log(res.status, await res.text());

A proxy refusal is not an exception here. With a wrong password, node-fetch resolved with res.status === 407, so check the status before reading the body. node-fetch 3 is an ES module. New code on a current Node release has little reason to add it: the built-in fetch with a dispatcher does the same job.

http and https modules with a proxy agent

The core modules take the same agents through the agent option:

import https from "node:https";
import { HttpsProxyAgent } from "https-proxy-agent";

const agent = new HttpsProxyAgent("http://USERNAME:PASSWORD@HOST:PORT", { keepAlive: true });

https
  .get("https://api.ipify.org", { agent }, (res) => {
    let body = "";
    res.on("data", (chunk) => (body += chunk));
    res.on("end", () => {
      console.log(res.statusCode, body);
      agent.destroy();
    });
  })
  .on("error", (error) => console.error(error.code, error.message));

The agent packages are named for the target: https-proxy-agent for https:// URLs, http-proxy-agent for http:// URLs. Both take an http:// proxy URL. Handing https.get the HTTP one sent the proxy a plain GET http://api.ipify.org:443/ in our test, not a tunnel. An https:// proxy URL starts TLS with a listener that answers in plain text, and fails with EPROTO and "packet length too long". Current versions export named classes (import { HttpsProxyAgent }); the axios guide has the import syntax for each major version.

From Node 24.5 and 22.21 the built-in agents can do this with no package, through the proxyEnv option:

import https from "node:https";

const agent = new https.Agent({
  keepAlive: true,
  proxyEnv: { HTTPS_PROXY: "http://USERNAME:PASSWORD@HOST:PORT" },
});

https
  .get("https://api.ipify.org", { agent }, (res) => {
    let body = "";
    res.on("data", (chunk) => (body += chunk));
    res.on("end", () => {
      console.log(res.statusCode, body);
      agent.destroy();
    });
  })
  .on("error", (error) => console.error(error.code, error.message));

proxyEnv takes the same keys as the environment (HTTP_PROXY, HTTPS_PROXY, NO_PROXY), so proxyEnv: process.env makes one agent follow the shell while the rest of the process stays direct.

SOCKS5 proxy in Node.js

Which package you need depends on whether the client takes agents or dispatchers.

Agent-based clients (http, https, got, node-fetch, axios) use socks-proxy-agent. One agent serves both schemes, because SOCKS5 carries any TCP connection:

import got from "got";
import { SocksProxyAgent } from "socks-proxy-agent";

const agent = new SocksProxyAgent("socks5h://USERNAME:PASSWORD@HOST:SOCKS_PORT");

const body = await got("https://api.ipify.org", {
  agent: { http: agent, https: agent },
  timeout: { request: 30_000 },
}).text();
console.log(body);

Write socks5h, not socks5. With the h, the hostname goes to the proxy and is resolved at the exit. Without it, Node resolves the name on your machine and sends the proxy an IP address, which leaks the lookup to your resolver and returns geo-aware DNS answers for your location instead of the exit's.

fetch and undici use a dispatcher. undici has shipped Socks5ProxyAgent since 7.23, marked experimental, and it prints an ExperimentalWarning once per process:

import { fetch, Socks5ProxyAgent } from "undici";

const dispatcher = new Socks5ProxyAgent("socks5://USERNAME:PASSWORD@HOST:SOCKS_PORT");

const res = await fetch("https://api.ipify.org", { dispatcher });
console.log(res.status, await res.text());

await dispatcher.close();

Here the scheme is socks5://, and undici 8.12 rejects socks5h:// as an invalid protocol. The DNS behavior is the safe one regardless: our test SOCKS5 server received the hostname, not an address. ProxyAgent accepts a socks5:// URL too and hands it to the same class.

The environment switch does not cover SOCKS, as noted above. On Node4, SOCKS5 uses the same host and the same credential as HTTP on a different port, shown when you switch the Connect card to SOCKS5. Every paid product has it, and the free tier is HTTP(S) only. SOCKS5 proxy setup lists the ports, and HTTP vs SOCKS5 covers when the protocol is worth choosing.

axios

axios is the one mainstream Node client with a proxy option of its own, and the one that reads HTTP_PROXY and HTTPS_PROXY without being asked. Both facts change how you configure it, and its handling of https:// targets changed in version 1.16.1. The axios proxy guide covers the proxy option, the agent setup with proxy: false, SOCKS5 and its error messages.

Proxy authentication in Node.js

Every client on this page accepts credentials inside the proxy URL and turns them into a Proxy-Authorization: Basic header on the CONNECT, or on the request itself for http:// targets. Percent-encode each half, or a password containing @, :, / or # breaks the URL:

import { fetch, ProxyAgent } from "undici";

const username = encodeURIComponent("USERNAME");
const password = encodeURIComponent("PASSWORD");

const dispatcher = new ProxyAgent(`http://${username}:${password}@HOST:PORT`);

const res = await fetch("https://api.ipify.org", { dispatcher });
console.log(res.status, await res.text());

await dispatcher.close();

undici also accepts the header value directly, which skips URL encoding: new ProxyAgent({ uri: "http://HOST:PORT", token: "Basic " + Buffer.from("USERNAME:PASSWORD").toString("base64") }).

On Node4, one credential works on every product your account has an active plan for. You can also whitelist your server's IP under Auth & IP Access in Account Settings and leave USERNAME:PASSWORD@ out of the URL. Whitelisting works on every product, and a whitelisted connection is untargeted, so country and session targeting need the credential. Authentication explains both methods.

Keep the URL out of source control. Read it from one variable of your own and stop at boot when it is missing, because the alternative is every request leaving quietly from your server's address:

import { ProxyAgent, setGlobalDispatcher } from "undici";

const proxyUrl = process.env.NODE4_PROXY_URL;
if (!proxyUrl) throw new Error("NODE4_PROXY_URL is not set");

setGlobalDispatcher(new ProxyAgent(proxyUrl));

Keep-alive, rotation and sticky sessions

A rotating gateway picks an exit for each connection: one per HTTPS tunnel or SOCKS5 connection, and one per plain-HTTP request. So whether a client reuses connections decides how often your address changes. The defaults differ, counted at the proxy over three requests to one host:

Client and setupTunnels openedExit
fetch or undici.request with one ProxyAgentUsually oneStays the same while the pooled tunnel lives
NODE_USE_ENV_PROXY=1 with https.getOneStays the same
https-proxy-agent with default options (got, node-fetch, https)ThreeA new pick each request
https-proxy-agent with keepAlive: trueOneStays the same
fetch with headers: { connection: "close" }, or undici.request with reset: trueThreeA new pick each request

For a new address on every request through the gateway, close the tunnel after each one:

import { fetch, ProxyAgent } from "undici";

const dispatcher = new ProxyAgent(
  "http://USERNAME:PASSWORD@gw-rotating_datacenter.node4.io:8083",
);

for (let i = 0; i < 3; i++) {
  const res = await fetch("https://api.ipify.org", {
    dispatcher,
    headers: { connection: "close" },
  });
  console.log(await res.text());
}

await dispatcher.close();

This prints three addresses. A later pick can repeat an earlier one.

To hold one address for a task, put a session id in the username instead. Every connection that carries the id gets the same exit, however the client pools:

import { fetch, ProxyAgent } from "undici";

function stickyDispatcher(sessionId) {
  return new ProxyAgent(
    `http://USERNAME-session-${sessionId}:PASSWORD@gw-rotating_datacenter.node4.io:8083`,
  );
}

const dispatcher = stickyDispatcher("job4182");

for (let i = 0; i < 2; i++) {
  const res = await fetch("https://api.ipify.org", {
    dispatcher,
    headers: { connection: "close" },
  });
  console.log(await res.text());
}

await dispatcher.close();

Both lines print the same address, even though each request opened its own tunnel. On Rotating Datacenter and Rotating Unmetered a session id holds its exit for up to 30 minutes from first use. Use one id per task, made of letters and digits. Sticky vs rotating sessions covers session lifetimes, and how to rotate proxy IPs compares gateway rotation with cycling a list of static proxies.

The gateway comes with two meters. Rotating Datacenter charges per gigabyte and starts at $5.90/month for 10 GB ($0.59/GB). Rotating Unmetered has no byte meter and charges for concurrent connections, starting at $29.00/month for 250 connections ($0.116 per connection), with its own hostname, gw-rotating_unmetered.node4.io, on port 8084. Both draw on one pool with exits in the US, Italy and Spain. On the connection-priced plan, an idle kept-alive tunnel still occupies a connection, so cap connections (undici) or maxSockets (agents) at or below your plan and close dispatchers when a job ends. Tiers are on rotating pricing and unmetered pricing.

Node.js proxy errors and fixes

The same proxy refusal reads differently in every client. Each row below was produced on purpose against a test proxy.

What you seeClientCauseFix
TypeError: fetch failed, with a cause that says only that the request was canceled (undici spells it with a double l)fetch, undiciThe proxy refused the CONNECT: wrong credentials (407) or a connection limit (429). undici does not surface the statusTest the same URL with curl -x to see the status. See the 407 guide
ERR_PROXY_TUNNEL, "Failed to establish tunnel ... 407"https with NODE_USE_ENV_PROXY or proxyEnvSame refusal, with the status in the messageFix the credentials in the variable
A response with status 407http:// targets, node-fetch, https with https-proxy-agentSame refusal, delivered as a responseCheck res.status before using the body
HTTPError, "status code 407" or "status code 429"gotSame refusalFix credentials, or lower concurrency
fetch failed, cause invalid onRequestStart methodBuilt-in fetchA dispatcher from a different undici majorImport fetch from undici, or use setGlobalDispatcher
fetch failed, cause ECONNREFUSEDAnyNothing accepted the connection to the proxyCheck host, port and outbound firewall
ERR_SSL_PACKET_LENGTH_TOO_LONG, or EPROTO "packet length too long"AnyThe proxy URL starts with https://Use http:// in the proxy URL
Invalid URL protocol at startupNODE_USE_ENV_PROXYA socks5:// URL in HTTPS_PROXYUse an HTTP proxy URL, or a SOCKS dispatcher in code
UND_ERR_SOCKS5_AUTH_FAILED, Socks5 Authentication failed, or "not allowed" repliesundici, socks-proxy-agentSOCKS5 refusal: wrong credentials, a free account on the SOCKS5 port, or a plan at its connection limitCheck credentials and plan
TimeoutError, "The operation was aborted due to timeout"fetchYour AbortSignal.timeout() firedRaise it, or retry on a new connection
502 from a rotating gateway after adding -country-AnyNo exits in the requested countryCheck the country code. A retry will not help
The script prints your own IPAnyThe proxy is not applied: no opt-in, an ignored agent on fetch, or undici loaded after the switchRun the check below at startup

fetch has no default timeout. Pass signal: AbortSignal.timeout(30_000) on every proxied call, so a stalled tunnel cannot hold a worker forever.

A request that succeeds through the proxy and still gets a 403 or a CAPTCHA is not a configuration error. The target is judging the address or the request, which why is my IP getting blocked covers. For everything below the HTTP layer, start with connection issues.

TLS through the CONNECT tunnel

After the CONNECT succeeds, your process performs the TLS handshake with the destination through the tunnel and validates the certificate against its own CA store. The proxy learns the hostname from the CONNECT line and nothing inside the encrypted stream.

So UNABLE_TO_VERIFY_LEAF_SIGNATURE and its relatives mean the destination's certificate chain did not validate: a misconfigured site, a missing intermediate, or software on your side re-signing traffic. NODE_TLS_REJECT_UNAUTHORIZED=0 disables verification for the whole process. Do not ship it. For a private CA, point NODE_EXTRA_CA_CERTS at its certificate file instead.

Verify the exit address

Finish every integration by asking an IP-echo service who you are, direct and proxied, and comparing. Accept only a 200 whose whole body is an IP address, because an error page that merely differs from your own address is not a proxied exit:

import { isIP } from "node:net";
import { Agent, ProxyAgent, fetch } from "undici";

const proxyAgent = new ProxyAgent("http://USERNAME:PASSWORD@HOST:PORT");
const directAgent = new Agent();

async function exitIp(dispatcher) {
  const res = await fetch("https://api.ipify.org", { dispatcher, signal: AbortSignal.timeout(30_000) });
  const body = (await res.text()).trim();
  if (res.status !== 200) throw new Error(`HTTP ${res.status}: ${body.slice(0, 80)}`);
  if (!isIP(body)) throw new Error(`not an IP address: ${body.slice(0, 80)}`);
  return body;
}

try {
  const [direct, proxied] = await Promise.all([exitIp(directAgent), exitIp(proxyAgent)]);
  if (direct === proxied) throw new Error("traffic is not leaving through the proxy");
  console.log("proxy exit:", proxied);
} finally {
  await Promise.all([directAgent.close(), proxyAgent.close()]);
}

Wire it into startup or CI. It catches a variable that stopped arriving, an opt-in flag lost in a deploy, and a dependency upgrade that changed proxy behavior. A static datacenter proxy echoes the same address every time; consecutive requests through a rotating gateway can differ. It proves the route to the echo service, not that a particular target accepts the proxy.

Runnable versions of the fetch, SOCKS5 and per-request rotation samples are in the Node.js folder of our examples repository on GitHub. If you are still choosing between static addresses you manage and a gateway that manages them for you, the datacenter proxies page and the pricing page lay out the options.