---
title: "How to use a proxy with Node.js fetch and axios"
url: https://proxy.wiki/guides/proxies-in-nodejs/
type: Guide
author: "proxy.wiki editorial"
published: 2026-08-29
updated: 2026-10-21
site: proxy.wiki
topics: ["Web scraping"]
license: CC BY 4.0; quote freely with attribution to https://proxy.wiki/
---

# How to use a proxy with Node.js fetch and axios

> Node fetch proxy setup that works: NODE_USE_ENV_PROXY, undici ProxyAgent, axios and got, with the version traps and exact errors from a logging proxy.

## Key takeaways

- Start Node 24 or later with NODE_USE_ENV_PROXY=1 to make fetch read HTTPS_PROXY; on 24.2.0 it did not cover http.get.
- On Node 24, an undici 8 ProxyAgent passed per call to the global fetch throws "invalid onRequestStart method". Use undici 7, undici's own fetch, or setGlobalDispatcher.
- axios 1.7.7 sent an HTTPS request to the proxy in cleartext, Authorization header included; 1.18.1 tunnelled it.
- Node's fetch tunnels even plain http:// URLs with CONNECT, which a proxy that limits CONNECT to TLS ports will refuse.
- Reuse one agent: 5 requests opened 1 tunnel through a shared agent and 5 with a new agent each.

Node’s built-in `fetch` ignores `HTTPS_PROXY` unless you start Node with `NODE_USE_ENV_PROXY=1` (Node 24.0.0 and later, or 22.21.0) or the `--use-env-proxy` flag. Without that, give fetch an undici `ProxyAgent` through `setGlobalDispatcher`. For axios, use its `proxy` option on 1.16.1 or later, or an `httpsAgent` with `proxy: false`. Every configuration on this page was run against a local proxy that logs each request, so “works” means the proxy recorded the connection. Two results contradict common advice: an undici 8 agent passed per call to Node 24’s fetch throws, and axios 1.7.7 sent an HTTPS request to the proxy in cleartext.

```
# Quickest route on Node 24.x: let fetch read the environment
NODE_USE_ENV_PROXY=1 HTTPS_PROXY=http://user:pass@gw.example.net:8000 node app.mjs
```

## Option 1: NODE_USE_ENV_PROXY

Without the flag, Node 24.2.0 sent the request straight to the destination and the proxy logged nothing. With it, global `fetch` honoured `http_proxy`, `https_proxy` and `no_proxy` in both lowercase and uppercase spellings. Two limits showed up in testing.

First, on 24.2.0 the flag changed `fetch` only. `http.get()` and `https.get()` still went direct. Node’s documentation lists built-in proxy support for the `http` and `https` modules as added in v24.5.0 and v22.21.0. On Node 18.13.0 the flag did nothing even for fetch. Check `node --version` before relying on it.

Second, Node’s fetch tunnels plain `http://` URLs. For `http://example.org/` our proxy log recorded `CONNECT example.org:80`, where curl, Python, Go and axios all sent `GET http://example.org/`. A proxy that only allows CONNECT to TLS ports, as Squid’s documented default rule `http_access deny CONNECT !SSL_ports` does, will refuse it. The bundled undici 7 `ProxyAgent` defaults to `proxyTunnel: true`; undici 8 tunnels only non-HTTP targets by default.

Node’s `no_proxy` matching also differs from curl and Python: a bare `example.org` entry is an exact host match and does not cover `api.example.org`. The full comparison is in [how no_proxy and http_proxy work across clients](/guides/proxy-environment-variables/).

## Option 2: a global dispatcher

When you want the proxy in code rather than in the environment, install undici and replace the global dispatcher:

```
// npm install undici@7   (tested with 7.29.0 on Node 24.2.0)
import { ProxyAgent, setGlobalDispatcher } from 'undici';

setGlobalDispatcher(new ProxyAgent('http://user:pass@gw.example.net:8000'));

const res = await fetch('https://example.com/');   // proxied
```

This is process-wide. Every `fetch` in the process now uses the proxy, including calls made by libraries you did not write. That suits a scraper and rarely suits a larger application.

## The version trap: undici 8 on Node 24

The obvious way to scope a proxy to one request is a per-call `dispatcher`. On Node 24.2.0 it worked or failed depending on which major version of undici you installed:

| Call | undici 5.29.0 | undici 7.16.0 / 7.29.0 | undici 8.10.2 |
| --- | --- | --- | --- |
| Global fetch, dispatcher: new ProxyAgent() | Works | Works | Throws |
| Global fetch after setGlobalDispatcher() | — | Works | Works |
| undici’s own fetch, per-call dispatcher | — | — | Works |
| Global fetch, new Dispatcher1Wrapper(new ProxyAgent()) | — | — | Works |

A dash means we did not run that combination. The failure reads like a network problem, which sends people off to check the network:

```
TypeError: fetch failed
  cause: InvalidArgumentError UND_ERR_INVALID_ARG: invalid onRequestStart method
```

The request never reached the proxy. The cause is a handler contract change between undici majors. undici’s support table lists 7.x as the version bundled in Node 24 and 8.x as the one bundled in Node 26. Node 24’s built-in fetch calls the dispatcher with the v7 handler contract, and the undici 8 agent rejects it at line 573 of `lib/core/util.js` in 8.10.2, where it checks for an `onRequestStart` method. `setGlobalDispatcher()` works across the gap because undici 8 deliberately mirrors the global dispatcher to the legacy slot through a `Dispatcher1Wrapper`, a behaviour its README documents.

Three fixes, all confirmed by the proxy log:

```
// Fix 1: match the major version Node bundles.
//   node -p process.versions.undici   prints 7.10.0 on Node 24.2.0, so: npm install undici@7

// Fixes 2 and 3 with undici 8 installed (tested with 8.10.2 on Node 24.2.0)
import { fetch as undiciFetch, ProxyAgent, Dispatcher1Wrapper } from 'undici';

const agent = new ProxyAgent('http://user:pass@gw.example.net:8000');

// Fix 2: undici's own fetch accepts an undici 8 dispatcher per call
const a = await undiciFetch('https://example.com/', { dispatcher: agent });

// Fix 3: keep Node's global fetch and wrap the agent, as the v7-to-v8 migration guide describes
const b = await fetch('https://example.com/', { dispatcher: new Dispatcher1Wrapper(agent) });
```

## What each client needs

| Client | How to proxy it | Scope | Tested version |
| --- | --- | --- | --- |
| Global fetch | NODE_USE_ENV_PROXY=1, or setGlobalDispatcher(new ProxyAgent(url)) | Whole process | Node 24.2.0 |
| undici fetch / request | dispatcher option per call | Per request | undici 8.10.2 |
| axios, built-in | proxy: { protocol, host, port, auth } | Per request or instance | axios 1.18.1 |
| axios, with an agent | httpsAgent plus proxy: false | Per request or instance | axios 1.18.1, https-proxy-agent 9.1.0 |
| got | agent: { http, https } | Per request or instance | got 11.8.6 |
| node:http / node:https | agent option | Per request | https-proxy-agent 7.0.6 and 9.1.0 |

## axios, and the cleartext trap before 1.16.1

```
import axios from 'axios';
import { HttpsProxyAgent } from 'https-proxy-agent';

// Option 1: axios's own proxy option (tested on axios 1.18.1)
const r1 = await axios.get(url, {
  proxy: { protocol: 'http', host: 'gw.example.net', port: 8000,
           auth: { username: 'user', password: 'pass' } },
});

// Option 2: an agent. Set proxy:false so axios does not apply its own handling as well.
const r2 = await axios.get(url, {
  httpsAgent: new HttpsProxyAgent('http://user:pass@gw.example.net:8000'),
  proxy: false,
});
```

Both produced a `CONNECT example.com:443` in the proxy log on 1.18.1. The version matters more than the option. We sent the same request with the built-in `proxy` option and an `Authorization: Bearer test-token-123` header through axios 1.7.7 and 1.18.1:

| axios | What the proxy received | Could the proxy read the request? |
| --- | --- | --- |
| 1.7.7 | GET https://example.com/, with Authorization: Bearer test-token-123 in its log | Yes, all of it |
| 1.18.1 | CONNECT example.com:443, then TLS | No, only the host and port |

With 1.7.7 the “HTTPS” request travelled to the proxy as plain HTTP, and our test proxy could answer it itself, so the client got a 200 that never came from example.com. The axios 1.16.1 release notes, dated 13 May 2026, list the fix under security: “HTTPS request data could be transmitted in cleartext to an HTTP proxy under certain configurations.” If you use axios’s `proxy` option with HTTPS targets on anything older, upgrade or switch to the agent form, which tunnelled correctly in our test.

axios also reads the proxy environment variables by default, on both versions, which plain Node does not. That is convenient and occasionally surprising when a process inherits a proxy it was not meant to use.

## got

```
import got from 'got';
import { HttpProxyAgent } from 'http-proxy-agent';
import { HttpsProxyAgent } from 'https-proxy-agent';

const PROXY = 'http://user:pass@gw.example.net:8000';
const res = await got(url, {
  agent: { http: new HttpProxyAgent(PROXY), https: new HttpsProxyAgent(PROXY) },
});
```

`agent` is an object keyed by protocol. Set both. With only `https` set, a request to an `http://` URL returned 200 and the proxy log stayed empty: it went direct, silently. With both set, the proxy logged `GET http://example.org/` for the plain URL and `CONNECT example.com:443` for the HTTPS one.

## node:http and node:https

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

https.get('https://example.com/', {
  agent: new HttpsProxyAgent('http://user:pass@gw.example.net:8000'),
  headers: { 'user-agent': 'my-tool/1.0' },
}, res => {
  console.log(res.statusCode);
  res.resume();
});
```

Use `node:https` with `HttpsProxyAgent` for `https://` targets and `node:http` with `HttpProxyAgent` for plain ones. Both https-proxy-agent 7.0.6 and 9.1.0 produced a logged CONNECT.

## SOCKS5: who resolves the hostname

For a [SOCKS5](/glossary/socks5/) proxy the question that matters is whether your machine or the proxy resolves the destination name. Resolving locally leaks the lookup to your own resolver and can pick an address that is wrong for the exit’s location. We ran a small SOCKS5 server that logs the address type each client sends: a domain name means the proxy resolves it, an IPv4 address means the client already did.

| Client and URL scheme | The SOCKS server received |
| --- | --- |
| curl 8.7.1, socks5:// (control) | IPv4 address |
| curl 8.7.1, socks5h:// (control) | Domain name |
| socks-proxy-agent 8.0.5, socks5:// | IPv4 address |
| socks-proxy-agent 8.0.5, socks5h:// | Domain name |
| undici Socks5ProxyAgent 7.29.0 and 8.10.2, socks5:// | Domain name |
| undici Socks5ProxyAgent 8.10.2, socks5h:// | Refused before connecting |

socks-proxy-agent follows curl’s convention, so write `socks5h://` to keep DNS at the proxy. It goes in the same `agent` position as the HTTP agents; we ran it with `node:https` and with axios (as `httpsAgent`, with `proxy: false`), with and without a username and password. undici’s agent always sent the hostname, even for `socks5://`, and rejected the `h` form outright:

```
InvalidArgumentError: Proxy URL must use socks5:// or socks:// protocol
```

It also prints `ExperimentalWarning: SOCKS5 proxy support is experimental and subject to change` once per process. Copying a `socks5h://` URL from a curl command into undici fails at construction, which is at least loud.

```
import { fetch, Socks5ProxyAgent } from 'undici';   // tested with 8.10.2
const res = await fetch('https://example.com/', {
  dispatcher: new Socks5ProxyAgent('socks5://user:pass@gw.example.net:1080'),
});
```

## Reuse the agent: a measured difference

Five identical HTTPS requests were sent twice through undici 8.10.2’s `request()`: once through a single shared `ProxyAgent`, once with a new agent per request. The proxy counted the tunnels:

_CONNECT tunnels opened by the proxy for 5 HTTPS requests, undici 8.10.2 on Node 24.2.0, 21 October 2026._

| Approach | CONNECT tunnels for 5 requests |
| --- | --- |
| One shared ProxyAgent | 1 |
| A new ProxyAgent per request | 5 |

```
// Create once, reuse
const agent = new ProxyAgent(PROXY);
for (const url of urls) {
  const r = await request(url, { dispatcher: agent });
  await r.body.dump();
}
```

Each extra tunnel is a TCP connection to the proxy plus a TLS handshake with the destination through it. The exception is deliberate rotation. A rotating gateway can only assign a new exit on a new tunnel, so a shared agent pins you to one exit, as shown in [sticky vs rotating proxies](/guides/rotating-vs-sticky-sessions/). If you want a different [exit](/glossary/exit-node/) per task, hold one agent per identity and reuse each.

## Reading the errors

undici wraps proxy failures, so the useful part sits two levels down in `err.cause`. This helper prints the whole chain:

```
function describe(err) {
  const chain = [];
  for (let e = err; e; e = e.cause) chain.push(`${e.name}${e.code ? ' ' + e.code : ''}: ${e.message}`);
  return chain.join('\n  caused by ');
}
```

Against a proxy that wanted credentials and got none, it printed:

```
TypeError: fetch failed
  caused by Error: Request was cancelled.
  caused by AbortError UND_ERR_ABORTED: Proxy response (407) !== 200 when HTTP Tunneling
```

Each row below was produced deliberately with undici 8.10.2 unless stated:

| What you see in the cause chain | Cause | Where to look |
| --- | --- | --- |
| ECONNREFUSED | Nothing listening on the proxy port | The port, or whether the proxy is running |
| ENOTFOUND getaddrinfo ENOTFOUND gw.invalid | The proxy hostname does not resolve | A typo in the gateway host, or your DNS |
| UND_ERR_CONNECT_TIMEOUT | Proxy URL written as https:// for a plain HTTP proxy | The scheme of the proxy URL |
| UND_ERR_INVALID_ARG invalid onRequestStart method | undici 8 agent passed to Node 24’s global fetch | The version trap above |
| UND_ERR_ABORTED Proxy response (407) !== 200 when HTTP Tunneling | The proxy rejected or did not receive credentials | The username format; see [403 vs 407 vs 429](/guides/403-vs-407-vs-429/) |
| HTTP 403 from the destination | The tunnel worked; the site refused you | What you sent, not the proxy |

The `https://` scheme row is worth remembering. The proxy waits for a request while your client waits for a TLS handshake, so neither speaks until the connect timeout fires, which we had set to 5,000 ms with `connectTimeout`. Node also printed `DeprecationWarning: Setting the TLS ServerName to an IP address is not permitted by RFC 6066` because the proxy was addressed by IP.

The 403 row came from GitHub’s API. undici’s low-level `request()` sends no User-Agent, and through a working proxy the API answered 403 with `Request forbidden by administrative rules. Please make sure your request has a User-Agent header`. The proxy log showed the CONNECT, so the proxy had done its job. Adding `headers: { 'user-agent': 'my-tool/1.0' }` returned 200. Default headers differ a lot between Node clients; [the default request headers study](/research/default-request-headers/) lists what each one sends.

## Proving the proxy is used

Do not infer it from the absence of errors. Ask an echo service for the address, and compare against the same call without the proxy:

```
import { fetch, ProxyAgent } from 'undici';

const viaProxy = await (await fetch('https://api.ipify.org',
  { dispatcher: new ProxyAgent(PROXY) })).text();
const direct   = await (await fetch('https://api.ipify.org')).text();

console.log({ viaProxy, direct });   // identical means no proxy was applied
```

On a [rotating endpoint](/glossary/rotating-proxy/) this reports one exit at one moment, not a property of the pool. Sample several times before concluding anything about a country.

## Practical notes

- **Set a timeout.** Pass `signal: AbortSignal.timeout(15000)` to fetch, or `timeout` to axios and got. An unbounded call on a hot path eventually hangs.

- **Keep credentials out of logs.** The proxy URL contains the password, and agents and config objects are easy to log whole while debugging.

- **Failed requests still cost traffic.** A 403 through a metered proxy is billable. See [bandwidth billing](/glossary/bandwidth-billing/).

- **Python has the same pitfalls in different shapes.** See [proxies in Python](/guides/proxies-in-python-requests-httpx/).

## How this was tested

Tested on macOS on 21 October 2026. A local forward proxy handled CONNECT, tunnelled to the real destination, and logged one line per request with the method, target and the username from `Proxy-Authorization`. A second instance demanded credentials and answered 407 without them. A separate local SOCKS5 server logged the address type each client sent. A configuration counted as working only where the log recorded the connection; a call that succeeded without a log line was treated as direct. curl controls confirmed each proxy logged correctly before any Node test ran. Each configuration was run once.

Versions: Node.js 24.2.0 (bundled undici 7.10.0) and 18.13.0; undici 5.29.0, 7.16.0, 7.29.0 and 8.10.2; axios 1.7.7 and 1.18.1; got 11.8.6; https-proxy-agent 7.0.6 and 9.1.0; http-proxy-agent 7.0.2; socks-proxy-agent 8.0.5; curl 8.7.1. Client behaviour changes between releases, so re-run the address comparison on your own versions.

## Frequently asked questions

### Why does HTTPS_PROXY not work in Node?

Node's HTTP clients do not read the proxy environment variables by default. On Node 24.0.0 and later, start the process with NODE_USE_ENV_PROXY=1 or --use-env-proxy and global fetch honours them. On 24.2.0 that did not extend to http.get; the documentation lists the http and https modules as gaining it in 24.5.0.

### What does "fetch failed" with "invalid onRequestStart method" mean?

You passed an undici 8 ProxyAgent as a per-call dispatcher to Node 24's built-in fetch, which bundles undici 7 and uses the older handler contract. Install undici@7, use undici's own fetch, or wrap the agent in Dispatcher1Wrapper. setGlobalDispatcher worked with both versions.

### Is axios's proxy option safe for HTTPS?

On 1.16.1 and later it tunnels with CONNECT. In our test axios 1.7.7 sent GET https://example.com/ to the proxy in cleartext, Authorization header included. The 1.16.1 release notes list the fix under security. Upgrade, or use httpsAgent with proxy: false.

### Why do I need proxy:false when I set httpsAgent in axios?

Because axios otherwise applies its own proxy handling, including any proxy it read from the environment, on top of the agent. Choose one mechanism: the agent with proxy set to false, or the proxy object with no agent.

### How do I keep DNS at the proxy with SOCKS5 in Node?

With socks-proxy-agent, use a socks5h:// URL; with socks5:// the client resolved the name itself. undici's Socks5ProxyAgent sent the hostname to the proxy even for socks5:// and rejects socks5h:// URLs.

### My proxied request returns 403. Is the proxy broken?

Probably not. A status code from the destination proves the tunnel worked. GitHub's API returned 403 through a working proxy because undici's request() sends no User-Agent; adding one returned 200.

## Sources

1. [Node.js CLI: NODE_USE_ENV_PROXY and --use-env-proxy](https://nodejs.org/api/cli.html#node_use_env_proxy1)
2. [Node.js http: built-in proxy support](https://nodejs.org/api/http.html#built-in-proxy-support)
3. [undici README: setGlobalDispatcher mirroring and the support table](https://github.com/nodejs/undici)
4. [undici: ProxyAgent](https://github.com/nodejs/undici/blob/main/docs/docs/api/ProxyAgent.md)
5. [undici: migrating from v7 to v8 and Dispatcher1Wrapper](https://github.com/nodejs/undici/blob/main/docs/docs/best-practices/migrating-from-v7-to-v8.md)
6. [undici: Socks5ProxyAgent](https://github.com/nodejs/undici/blob/main/docs/docs/api/Socks5ProxyAgent.md)
7. [axios v1.16.1 release notes: proxy cleartext fix](https://github.com/axios/axios/releases/tag/v1.16.1)
8. [https-proxy-agent](https://github.com/TooTallNate/proxy-agents/tree/main/packages/https-proxy-agent)
9. [socks-proxy-agent](https://github.com/TooTallNate/proxy-agents/tree/main/packages/socks-proxy-agent)
10. [got options: agent](https://github.com/sindresorhus/got/blob/main/documentation/2-options.md)
11. [RFC 9110, section 9.3.6: CONNECT](https://www.rfc-editor.org/rfc/rfc9110.html#section-9.3.6)
12. [Squid FAQ: CONNECT limited to SSL ports](https://wiki.squid-cache.org/SquidFaq/SecurityPitfalls)
