Skip to content

How to Set Up a Proxy in Node.js fetch

The built-in fetch in Node.js ignores proxy environment variables by default. This guide shows how to route it through a proxy with an undici dispatcher and test the result.

9 min readUpdated Nov 13, 2026By XPASS Editorial Team

How to Set Up a Proxy in Node.js fetch

Many Node.js developers are surprised the first time they set https_proxy in the environment, run a script that uses fetch, and see no effect at all. Curl, Python's requests library and many other clients read those variables by default, so the expectation is reasonable, but the global fetch in Node.js behaves differently. It is implemented on top of a library called undici, and out of the box it connects directly to the destination. This guide explains why, shows the dependable ways to route fetch through a proxy, covers authentication and timeouts, and ends with a routine for verifying that traffic really leaves through the proxy.

The usual caution applies. Use a proxy for lawful work: calling your own APIs from a specific network location, testing how your site responds to visitors from another region, or collecting public data you are permitted to collect. Follow the target's terms of service and local law, respect robots.txt and rate limits, and keep your request volume modest.

Why fetch ignores the proxy variables

The fetch function that ships with modern Node.js follows the web standard API, and web standards do not define proxy settings, because in a browser the network stack belongs to the browser or the operating system. Node.js implements the API through undici, an HTTP client with a pluggable component called a dispatcher. A dispatcher decides how a request is delivered: which sockets to open, whether to reuse connections, and whether to go through a proxy. The default dispatcher connects straight to the target host. Some recent Node.js releases add an opt-in switch for honoring proxy environment variables, but it depends on the exact version and is not something to rely on across the environments where your code may run. Check the documentation for your version, and when you need predictable behavior across machines, configure the dispatcher explicitly.

The proxy itself works as described in the MDN overview of proxy servers and tunneling. For an HTTPS destination the client sends CONNECT host:443 to the proxy, the proxy opens a tunnel, and TLS then runs end to end between your program and the destination. The proxy sees the host name and port but not the content of the page.

Before coding, gather the details from your dashboard or the proxy product page: host, port, protocol and authentication method. The examples use the placeholder proxy.example.net:8080.

The ProxyAgent approach

Install the undici package from npm:

npm install undici

Then create a ProxyAgent and hand it to undici's own fetch:

import { fetch, ProxyAgent } from "undici";

const dispatcher = new ProxyAgent("http://proxy.example.net:8080");

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

Using the fetch exported by the undici package, rather than the global one, matters. The global fetch is bundled with a particular undici version inside Node.js, and passing a dispatcher created by a different version of the package can fail in confusing ways. If both the dispatcher and the fetch come from the same installed package, they match.

If you prefer that every fetch call in the process uses the proxy without editing each call, set a global dispatcher:

import { setGlobalDispatcher, ProxyAgent } from "undici";

setGlobalDispatcher(new ProxyAgent("http://proxy.example.net:8080"));

This is convenient for a small script, but it affects every undici-based request in the process, including libraries you call. In an application that also talks to internal services, a per-request or per-client dispatcher is safer, because you can leave the internal calls on the default route.

Authentication

Providers usually authenticate with a source IP allowlist or with a username and password. With an allowlist you need no code change. With credentials, build a Basic authorization value and pass it as the token option:

import { fetch, ProxyAgent } from "undici";

const { PROXY_URL, PROXY_USER, PROXY_PASS } = process.env;
const token =
  "Basic " + Buffer.from(`${PROXY_USER}:${PROXY_PASS}`).toString("base64");

const dispatcher = new ProxyAgent({ uri: PROXY_URL, token });
const res = await fetch("https://example.com/", { dispatcher });

The token is sent to the proxy in the Proxy-Authorization header. Keep these points in mind:

  • Read the values from environment variables or a secret store. Do not commit them, and do not log the token or the ProxyAgent options.
  • Basic authentication is only encoded, not encrypted. If you reach the proxy over plain HTTP, anyone on the path to the proxy can read it. Prefer an encrypted connection to the proxy if your provider offers one.
  • If the proxy replies 407 Proxy Authentication Required, the credentials are missing or wrong, or your IP address is not on the allowlist.

Timeouts, redirects and error handling

A fetch through a proxy has one more hop that can fail or stall, so set limits. The AbortSignal.timeout helper gives you a simple deadline:

const res = await fetch("https://example.com/", {
  dispatcher,
  signal: AbortSignal.timeout(15_000),
});
if (!res.ok) {
  throw new Error(`Unexpected status ${res.status}`);
}

Remember that fetch only rejects its promise for network-level failures such as a refused connection or a timeout. An HTTP error status like 407, 429 or 502 still resolves, so always check res.ok or res.status. By default fetch follows redirects, and each hop also goes through the dispatcher. If you need to inspect a redirect yourself, pass redirect: "manual".

Treat status codes as information. 407 means the proxy wants credentials. 502, 503 and 504 often mean the proxy could not reach the destination or is overloaded, so retry sparingly with a growing delay rather than in a tight loop. 429 Too Many Requests from the destination means you must slow down, and you should honor a Retry-After header as described in RFC 9110. A proxy is never a reason to ignore a rate limit.

Verifying the route

Make verification a habit. Write a tiny script that requests an endpoint returning the caller's public IP address, once directly and once through the dispatcher:

import { fetch, ProxyAgent } from "undici";

const echo = "https://ip-echo.example.com/";
const direct = await (await fetch(echo)).text();
const proxied = await (
  await fetch(echo, { dispatcher: new ProxyAgent(process.env.PROXY_URL) })
).text();

console.log({ direct: direct.trim(), proxied: proxied.trim() });
if (direct.trim() === proxied.trim()) {
  throw new Error("The proxy is not being used");
}

Here ip-echo.example.com is a placeholder for an echo endpoint you host or your team already trusts. If your provider documents the exit region, compare it with what the echo service reports. Run the same check at the start of a deployment, because environment differences such as a missing variable are a common cause of silent direct connections. It also helps to confirm the command-line path first; the guide to sending an HTTP request through a proxy with cURL shows how to separate credential and network problems from code problems.

A plain example: checking a regional price page

Suppose you run a store and want to confirm that the currency and shipping notice on your own product page change for visitors in another country. A careful plan:

  1. Obtain an HTTP proxy endpoint with an exit in the target country and store its URL and credentials in environment variables.
  2. Write a script that fetches the product page through a ProxyAgent with a custom User-Agent describing your test tool.
  3. Run the verification script above to confirm the exit address differs from your own.
  4. Fetch the page, parse the currency element, and assert on the expected text.
  5. Run the same script without the dispatcher and confirm the output differs, which proves the regional logic is what you tested.
  6. Add a short delay between pages and stop at a small number of URLs; this is a check of your own site, not a crawl.

Before deploying, work through these points once per project, and again after any dependency upgrade:

  1. Confirm which Node.js version and which undici version are installed, and note them in your repository documentation.
  2. Confirm that the fetch and the ProxyAgent are imported from the same package.
  3. Run the direct-versus-proxied comparison and check that the two addresses differ.
  4. Confirm that credentials come from environment variables or a secret store and that none appear in logs.
  5. Set a timeout on every request and decide, in code, what happens after the second failed attempt.
  6. Decide whether the dispatcher is created once and reused, and where it is closed.
  7. Write down the expected request volume and confirm it stays within what the target site and your plan allow.

Common mistakes follow a pattern. The first is assuming that the environment variable works because curl honored it on the same machine. The second is creating a new ProxyAgent inside a loop, which opens a new connection pool for every request and slowly exhausts sockets. The third is catching an error and retrying immediately, which turns a short outage into a burst of traffic. The fourth is testing only the happy path: also try a wrong password on purpose and confirm that your code reports the 407 clearly instead of hiding it.

Also keep a small test for the failure paths. Point the script at a closed port and confirm that your code reports a connection error within the timeout you set. Use a wrong password on purpose and confirm that the message mentions the proxy rather than the destination site. These two checks take a few minutes and save a long debugging session later, because they show whether your error handling distinguishes a proxy problem from a target problem.

Limits and what to watch for

  • Version differences. Node.js and undici evolve quickly. Pin the undici version in your lockfile and test after upgrades.
  • Mixing fetch implementations. Use the fetch and ProxyAgent from the same package, or you may see errors about invalid dispatchers.
  • Connection reuse. A dispatcher keeps connections alive. Create it once and reuse it instead of creating a new one per request, and close it with await dispatcher.close() when your program is finished.
  • Rotating exits. If the endpoint changes address between requests, flows that rely on a session may break. Use a sticky or dedicated address for those flows if your provider offers one.
  • SOCKS5. Undici's ProxyAgent is meant for HTTP proxies. A SOCKS5 proxy, defined in RFC 1928, generally needs a separate agent library with the older http or https modules. If you want to stay on fetch, choose an HTTP endpoint. Check the plan page for which protocols are included.
  • Concurrency. Many parallel requests through one endpoint may exceed the connection limits of your plan. Limit concurrency in your code and review what the plan includes.
  • Secrets in logs. Error objects and debug output can include proxy URLs. Scrub them before logging.

If your project already uses Axios for API calls, it has its own proxy handling and different pitfalls, covered in setting up an Axios proxy for API work. For crawling public pages in Python with polite settings, see using a proxy with Scrapy for permitted public data.

Summary

The global fetch in Node.js does not read proxy environment variables by default, so you route it explicitly with an undici ProxyAgent, either per request through the dispatcher option or globally with setGlobalDispatcher. Use fetch and ProxyAgent from the same package, pass credentials as a Basic token read from the environment, set timeouts with AbortSignal.timeout, and check res.ok because HTTP errors do not reject the promise. Verify the exit address with an IP echo page before trusting results, respect rate limits and site terms, and keep the work lawful. When you are ready to choose an endpoint, the details of what each plan includes are on the proxy page.

Frequently asked questions

Does the built-in fetch in Node.js use the http_proxy variable?

Not by default. The global fetch in Node.js is built on undici and does not read proxy environment variables unless your Node.js version offers and you enable an opt-in setting. The reliable approach is to pass a proxy dispatcher explicitly.

How do I route fetch through an HTTP proxy?

Install the undici package, create a ProxyAgent with the proxy address, and either pass it as the dispatcher option of undici's own fetch or set it as the global dispatcher. Requests to HTTPS sites are tunneled through the proxy with CONNECT.

How do I send a proxy username and password?

Give the ProxyAgent a token containing a Basic authorization value built from your credentials, or use a proxy address that includes them if your undici version supports it. Read the values from environment variables and never commit them.

Can fetch use a SOCKS5 proxy?

Undici's ProxyAgent is designed for HTTP proxies. For SOCKS5 you typically use a library that provides a SOCKS agent together with the older http or https modules, or choose an HTTP endpoint from your provider.

About the author

Bob Kanokphon Thongdee, founder of XPASS VPN

Bob Kanokphon Thongdee

  • Founder of XPASS VPN
  • Co-founder of eSIMonline.asia
  • More than 7 years in online marketing
  • Founder of Cojourney Visa and Cojourney Travel

Need a proxy for this?

XPASS Proxy sells residential proxy traffic by the gigabyte, with the price shown before you pay.

See proxy plans

Keep reading

Proxy Guides

How to Send an HTTP Request Through a Proxy with cURL

Use cURL to test an HTTP or SOCKS5 proxy from the command line: the right flags, authentication, environment variables, a verification routine and how to read errors.

9 min read

Proxy Guides

How to Set Up an Axios Proxy for API Work

A practical guide to routing Axios requests through a proxy in Node.js, from the built-in proxy option to agents, environment variables, timeouts and testing.

9 min read

Proxy Guides

How to Use a Proxy with Scrapy for Permitted Public Data

Learn how to route Scrapy spiders through a proxy for public data you are allowed to collect, using request meta, a downloader middleware and polite crawl settings.

10 min read