How to Use an HTTP Proxy in Node.js with Undici

Undici lets you send a Node.js request through an HTTP proxy using ProxyAgent. The example below runs the same request directly and through the proxy so you can compare exit IPs and see which connection failed.

Terminal display beside two rack servers on a green workbench

Install Undici and set the proxy address

Use Node.js 24 LTS or another supported release that meets Undici 8’s Node.js 22.19.0 minimum. In a new project directory, confirm the runtime and install the package. Node’s built-in fetch uses a bundled copy of Undici. The installed package gives this example an explicit ProxyAgent and a matching fetch implementation. Undici version support.

node --version
npm init -y
npm install undici@8

Set PROXY_URL to the scheme, hostname and port your provider supplied, such as http://gateway.example:8080. To run the example from PowerShell or a Unix shell, you can put that setting in a local proxy.env file and load it with Node.

PROXY_URL=http://gateway.example:8080

Use the environment provided by your secret manager for PROXY_USER and PROXY_PASSWORD if your provider requires Basic authentication. Keep the URL free of credentials. If you supply credentials through a local environment file, limit access to that file and keep it out of version control.

Compare your direct IP and the proxy exit IP

Save this as proxy-ip.mjs. The first request uses an explicit direct Agent. The second uses a ProxyAgent passed as the dispatcher for that request. Each request gets a fresh 12-second deadline, and the script closes both agents when it finishes.

import { Buffer } from 'node:buffer';
import { isIP } from 'node:net';
import { Agent, ProxyAgent, fetch } from 'undici';

const { PROXY_URL, PROXY_USER, PROXY_PASSWORD } = process.env;
if (!PROXY_URL || (PROXY_USER === undefined) !== (PROXY_PASSWORD === undefined)) {
  console.error('Set PROXY_URL and supply both proxy credentials if needed.');
  process.exit(1);
}

const uri = URL.parse(PROXY_URL);
if (!uri || !['http:', 'https:'].includes(uri.protocol) || uri.username || uri.password) {
  console.error('Use an HTTP or HTTPS proxy URL without embedded credentials.');
  process.exit(1);
}

const token = PROXY_USER === undefined
  ? undefined
  : `Basic ${Buffer.from(`${PROXY_USER}:${PROXY_PASSWORD}`, 'utf8').toString('base64')}`;
const proxy = new ProxyAgent({ uri: uri.href, token });
const direct = new Agent();

async function showIp(label, dispatcher) {
  const response = await fetch('https://testmyproxies.com/api/my-ip', {
    dispatcher,
    signal: AbortSignal.timeout(12_000),
    redirect: 'error',
  });

  if (!response.ok) {
    await response.body?.cancel();
    throw new Error(`${label}: IP endpoint returned HTTP ${response.status}`);
  }

  const { ip } = await response.json();
  if (typeof ip !== 'string' || isIP(ip) === 0) {
    throw new Error(`${label}: IP endpoint returned an unexpected response`);
  }

  console.log(`${label}: ${ip}`);
}

try {
  await showIp('Direct', direct);
  await showIp('Proxy', proxy);
} catch (error) {
  console.error(error.cause?.message ?? error.message);
  process.exitCode = 1;
} finally {
  await Promise.all([direct.close(), proxy.close()]);
}
node --env-file=proxy.env proxy-ip.mjs

If the variables are already set in your shell or service runner, use node proxy-ip.mjs. Compare the two addresses with the exit IP your provider reports. Different addresses show that TestMyProxies saw different source IPs on those two requests. Identical addresses warrant a look at the egress configuration because the two routes can share a public IP. For a rotating proxy, check the provider’s session settings and the IP reported on each run.

For a long-running process, keep an agent for each proxy configuration and reuse it across requests. Pass that dispatcher only where the app should use the proxy. This keeps the routing decision at the request instead of changing it for every fetch in the process. Close the agent when the application no longer needs it. Undici ProxyAgent reference.

Understand CONNECT and the two TLS connections

The proxy URL describes how Node reaches the proxy. With an http:// proxy and an https:// destination, Undici sends an HTTP CONNECT request asking the proxy to open a tunnel. Node then negotiates destination TLS through that tunnel. With an https:// proxy URL, Node first negotiates TLS to the proxy, then sends CONNECT and negotiates TLS to the destination through the tunnel.

Basic proxy authentication encodes the username and password with Base64. Over a plaintext proxy connection, those credentials are visible on that link. Use a provider-supported HTTPS proxy endpoint when the connection to the proxy needs encryption. If a managed proxy uses a private certificate authority, get the approved CA from its administrator. Undici’s proxyTls settings apply to that connection and requestTls settings apply to the destination. Keep certificate verification enabled. Compare HTTP, HTTPS and SOCKS5 proxies.

Troubleshoot a Node.js proxy error

  • HTTP 407 during CONNECT. The proxy is challenging for credentials before the request reaches TestMyProxies. Check the proxy’s scheme, account details and any source IP allowlist. The code supplies credentials in the agent’s token option, which uses them for proxy authentication. HTTP 407 Proxy Authentication Required.
  • DNS error, connection refused or timeout. Check the proxy hostname and port from the machine that runs Node. Compare that request with the direct result. If the direct request also fails, check whether the machine can reach the lookup endpoint and has a working resolver.
  • Certificate error. Check which connection failed. With an HTTPS proxy, a hostname mismatch can occur at the proxy before the tunnel opens. A failed hostname or trust check after CONNECT concerns the destination connection.

Run the same lookup from the same machine using cURL to compare the proxy address and observed exit IP. For a Python application, repeat the check using Requests. Test a proxy with cURL. Use a proxy in Python Requests.

All proxy testing guides · Open the proxy tester