How to use a proxy with Node.js fetch and undici
Node.js's built-in fetch runs on undici and has no agent option, so the usual https-proxy-agent tricks don't work. Instead, pass an undici ProxyAgent as the dispatcher, or turn on Node's built-in proxy support. This guide covers both, plus sticky sessions, targeting, SOCKS5 and error handling.
Updated 9 November 2026
Prerequisites
- Node.js 22 or newer. Current undici (8.x) needs Node 22.19+; Node's environment-variable proxy support for
fetcharrived in Node 24 (and was backported to 22.21). npm i undiciforProxyAgent. Importfetchfromundicitoo, so the dispatcher andfetchcome from the same version; mixing the npm package with Node's bundled copy can fail in confusing ways.- A proxy login from the dashboard under Logins, shown as
USERandPASS.
Typical uses: monitoring public pages and APIs, localized QA, and lightweight data collection without a headless browser.
Basic HTTP proxy
Create a ProxyAgent with the proxy URL and pass it as dispatcher. HTTPS targets are tunneled with CONNECT, so TLS stays end to end; plain HTTP targets are forwarded. If you can't change the code, Node 24 can read HTTP_PROXY/HTTPS_PROXY when started with NODE_USE_ENV_PROXY=1 or --use-env-proxy.
// npm i undici
import { fetch, ProxyAgent } from "undici";
const dispatcher = new ProxyAgent("http://USER-cc-us:PASS@gw.hyperproxy.io:8888");
const res = await fetch("https://api.ipify.org", { dispatcher });
console.log(await res.text()); // the exit IPAuthentication
Put the credentials in the proxy URL; undici turns them into a Proxy-Authorization header. Alternatively, pass { uri, token } where token is a ready-made header value such as Basic <base64>. Encode special characters in the password with encodeURIComponent().
Rotating vs sticky IPs
The gateway gives every new connection a new exit. A ProxyAgent keeps tunnels open and reuses them per host, so requests through one agent to the same site usually share an exit. For a guaranteed new IP, use a fresh agent and close it afterwards, or put a unique session id in each username. For a stable IP, add a session id: same id, same exit, for 5 minutes by default or up to 120 with ttl.
import { fetch, ProxyAgent } from "undici";
const proxy = "http://USER-cc-us:PASS@gw.hyperproxy.io:8888";
// ProxyAgent keeps tunnels alive per host; a new agent means a new connection and a new exit
for (let i = 0; i < 3; i++) {
const dispatcher = new ProxyAgent(proxy);
const res = await fetch("https://api.ipify.org", { dispatcher });
console.log(await res.text());
await dispatcher.close();
}Country and city targeting
| Username | Exit |
|---|---|
USER-cc-us | United States |
USER-cc-us-city-new_york | New York |
USER-cc-us-region-california | California |
USER-cc-de-asn-3320 | A specific German network |
USER-cont-eu | Anywhere in Europe |
USER-cc-us-city-houston-strict-false | Houston, or the rest of the US |
Create one agent per username and choose it per request. See Targeting for all options.
SOCKS5
Recent undici releases include Socks5ProxyAgent (still marked experimental), and ProxyAgent hands socks5:// URLs to it. It sends hostnames to the proxy, so DNS is resolved remotely, as with socks5h elsewhere. The HTTP endpoint is the more established path in Node.js.
import { fetch, Socks5ProxyAgent } from "undici";
// experimental in undici; hostnames are resolved by the proxy
const dispatcher = new Socks5ProxyAgent("socks5://USER-cc-de:PASS@gw.hyperproxy.io:8888");
const res = await fetch("https://api.ipify.org", { dispatcher });
console.log(await res.text());Concurrency
One agent can serve many concurrent requests. Cap its open connections per host with connections, run a fixed number of workers, and always consume or cancel response bodies so connections are released.
import { fetch, ProxyAgent } from "undici";
const dispatcher = new ProxyAgent({
uri: "http://USER-cc-us:PASS@gw.hyperproxy.io:8888",
connections: 10, // max open connections per target host
});
const urls = Array.from({ length: 100 }, (_, i) => `https://example.com/page/${i}`);
async function worker() {
for (let url = urls.shift(); url; url = urls.shift()) {
const res = await fetch(url, { dispatcher, signal: AbortSignal.timeout(30_000) });
await res.arrayBuffer(); // always consume the body so the connection is freed
console.log(url, res.status);
}
}
await Promise.all(Array.from({ length: 10 }, worker));
await dispatcher.close();Error handling and retries
When the gateway refuses a CONNECT, fetch rejects with TypeError: fetch failed, and err.cause holds the reason, for example Proxy response (404) !== 200 when HTTP Tunneling. For plain HTTP targets the status arrives as a normal response. Map it with Errors:
- 407: wrong login, an invalid or repeated option, or no balance. Don't retry.
- 404: no exit matches; widen the targeting or add
strict-false. - 403: the target is not allowed. 400: a malformed request.
- 429: back off. 502 / 504: retry; without a session each retry gets a new exit.
const RETRYABLE = new Set([429, 502, 504]);
async function getWithRetry(url, dispatcher, attempts = 4) {
for (let i = 0; ; i++) {
try {
const res = await fetch(url, { dispatcher, signal: AbortSignal.timeout(30_000) });
if (!RETRYABLE.has(res.status) || i + 1 >= attempts) return res;
await res.arrayBuffer();
} catch (err) {
// fetch rejects with TypeError("fetch failed"); the reason is in err.cause, e.g.
// "Proxy response (404) !== 200 when HTTP Tunneling"
const reason = String(err.cause?.message ?? err);
if (/\((40[0347])\)/.test(reason) || i + 1 >= attempts) throw err;
}
await new Promise((r) => setTimeout(r, 500 * 2 ** i)); // new exit unless sticky
}
}Verify the exit IP
Fetch https://api.ipify.org with the dispatcher. To check the environment-variable setup, compare node -e "fetch('https://api.ipify.org').then(r => r.text()).then(console.log)" with and without NODE_USE_ENV_PROXY=1.
Troubleshooting
- The proxy is ignored: built-in
fetchignoresHTTP_PROXYunlessNODE_USE_ENV_PROXY=1is set, and it ignores anagentoption entirely. - Odd handler or dispatcher errors: the dispatcher and
fetchcome from different undici versions; import both fromundici. - Same IP on every request: connection reuse; see the rotating example.
- Process doesn't exit: call
dispatcher.close()when you're done.
FAQ
Does node-fetch work the same way?
No. The node-fetch package uses Node's http module, so it takes an agent such as HttpsProxyAgent, like axios.
Does this work in Bun or Deno?
Their fetch implementations have their own proxy options, so check their docs. Bun, for example, accepts a proxy option on fetch.
Can I use one proxy for some hosts only?
Pass the dispatcher only on those requests, or use EnvHttpProxyAgent with NO_PROXY.
Where are more examples?
See Examples, the Puppeteer guide and the Crawlee guide.
Try it on your own workload
Sign up with GitHub or Google, create a proxy login and send your first request in a minute.
More proxy integration guides
- Python requests — Rotating and sticky residential proxies with Python requests, including SOCKS5 and retries.
- Python httpx — Sync and async httpx through a residential proxy with the proxy= argument and SOCKS5.
- Python aiohttp — High-concurrency aiohttp requests through rotating or sticky residential IPs.
- Scrapy — Route Scrapy spiders through residential proxies with request.meta and a middleware.
- Playwright — Run Playwright through residential proxies, per browser or per context, with sticky sessions.
- Puppeteer — Launch Puppeteer behind an authenticated residential proxy with page.authenticate.
- Crawlee — Map Crawlee sessions to sticky residential IPs and target countries per request.
- Node.js axios — Send axios requests through HTTP and SOCKS5 residential proxies with proxy agents.
- Go net/http — Configure Go's http.Transport for HTTP and SOCKS5 residential proxies.
- curl & SOCKS5 — Use curl with HTTP and SOCKS5 proxies, and test targeting from the command line.