Using a proxy in Node.js: fetch, axios, got and SOCKS5 with a username and password
In this article
Node.js doesn't send requests through a proxy unless you tell it to. The simplest way today is undici's ProxyAgent with undici's own fetch, which reads the username and password straight from a URL like http://USER:PASS@HOST:PORT. axios has its own proxy option, got takes proxy agents, and SOCKS5 works through socks-proxy-agent. Every example below was tested on 18 November 2026 with Node.js 24 against a test proxy that requires a password.
Which method should you use?
| You use | Install | Notes |
|---|---|---|
fetch |
undici |
Import fetch and ProxyAgent from undici together |
| No extra package | Nothing | NODE_USE_ENV_PROXY=1, still experimental |
| axios | axios |
proxy option; HTTPS sites need axios 1.16.1 or newer |
| got | got, hpagent |
got 16 is ESM-only and needs Node 22 |
| SOCKS5 port | socks-proxy-agent |
Use socks5h:// so the proxy resolves names |
Each example reads the proxy from a PROXY environment variable, so the password stays out of your code. Save the files with the .mjs extension to use import.
fetch with undici
Install with npm install undici:
import { fetch, ProxyAgent } from "undici";
const proxy = new ProxyAgent(process.env.PROXY); // http://USER:PASS@HOST:PORT
const res = await fetch("https://65proxy.com/ip.json", { dispatcher: proxy });
console.log(await res.json());The result shows the IP the site sees and its country (SG for a Singapore proxy). Two things to get right:
- Import
fetchfrom undici too. Passing undici 8'sProxyAgentto Node 24's built-infetchfails withTypeError: fetch failed, because the two undici versions don't match. - Encode special characters in the password:
@becomes%40,:becomes%3A.encodeURIComponent(password)does it for you.
To send every fetch call in the program through the proxy, including the built-in one, set a global dispatcher once:
import { ProxyAgent, setGlobalDispatcher } from "undici";
setGlobalDispatcher(new ProxyAgent(process.env.PROXY));
const res = await fetch("https://65proxy.com/ip.json"); // Node's built-in fetch
console.log(await res.json());Without packages: NODE_USE_ENV_PROXY
Recent Node.js versions can read the usual proxy variables themselves when you turn it on:
NODE_USE_ENV_PROXY=1 HTTP_PROXY="http://USER:PASS@HOST:PORT" HTTPS_PROXY="http://USER:PASS@HOST:PORT" node app.mjsOn Windows PowerShell, set $env:NODE_USE_ENV_PROXY = "1" and the two proxy variables before running node. What to know:
- Versions: it covers
fetchfrom Node 24.0 and alsohttpandhttpsfrom Node 24.5 (and 22.21). The--use-env-proxyflag does the same. - Status: the feature is still marked experimental in Node's documentation.
- HTTP proxies only: don't put a SOCKS5 address in these variables.
NO_PROXYlists sites that should skip the proxy.
axios
axios has a proxy option with the login in its own auth field:
import axios from "axios";
const res = await axios.get("https://65proxy.com/ip.json", {
proxy: {
protocol: "http",
host: process.env.PROXY_HOST,
port: Number(process.env.PROXY_PORT),
auth: { username: process.env.PROXY_USER, password: process.env.PROXY_PASS },
},
timeout: 30000,
});
console.log(res.data);Check your axios version with npm ls axios. Before 1.16.1, axios sent requests for HTTPS sites to the proxy without opening a tunnel, and they failed. If you must stay on an older version, or want the same code for every client, use an agent and turn axios's own proxy handling off:
import axios from "axios";
import { HttpsProxyAgent } from "https-proxy-agent";
const agent = new HttpsProxyAgent(process.env.PROXY);
const res = await axios.get("https://65proxy.com/ip.json", { httpsAgent: agent, proxy: false });
console.log(res.data);Always set proxy: false when you pass your own agent.
got
got 16 recommends the hpagent package (npm install got hpagent). Give it one agent for HTTP sites and one for HTTPS sites:
import got from "got";
import { HttpProxyAgent, HttpsProxyAgent } from "hpagent";
const proxy = process.env.PROXY;
const data = await got("https://65proxy.com/ip.json", {
agent: {
http: new HttpProxyAgent({ proxy }),
https: new HttpsProxyAgent({ proxy }),
},
timeout: { request: 30000 },
}).json();
console.log(data);Careful: hpagent and https-proxy-agent both export a class named HttpsProxyAgent, but hpagent's takes an object ({ proxy }) while the other takes the URL directly.
SOCKS5 with socks-proxy-agent
To use the proxy's SOCKS5 port, install socks-proxy-agent and write the address with socks5h://, which makes the proxy look up site names itself:
import https from "node:https";
import { SocksProxyAgent } from "socks-proxy-agent";
const agent = new SocksProxyAgent(process.env.SOCKS_PROXY); // socks5h://USER:PASS@HOST:PORT
https.get("https://65proxy.com/ip.json", { agent }, (res) => {
res.pipe(process.stdout);
});The same agent works elsewhere:
- axios:
{ httpAgent: agent, httpsAgent: agent, proxy: false }. - got:
{ agent: { http: agent, https: agent } }.
Why socks5h:// and not socks5://: with socks5://, your own machine resolves the name and may hand the proxy an IPv6 address, which an IPv4-only 4G line can't reach. The details are in proxy keeps disconnecting and socks5 or socks5h. undici also has a Socks5ProxyAgent, but it is still marked experimental.
Timeouts and retries
Mobile lines have slow moments and short drops, so give every request a timeout and retry the ones that fail on the connection. This helper waits 5, 10, 20 and 40 seconds between tries:
import { fetch, ProxyAgent } from "undici";
const proxy = new ProxyAgent(process.env.PROXY);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// undici wraps the real reason in err.cause, sometimes twice
function reason(err) {
while (err.cause) err = err.cause;
return err.message;
}
async function get(url, tries = 5) {
for (let attempt = 1; attempt <= tries; attempt++) {
try {
const res = await fetch(url, { dispatcher: proxy, signal: AbortSignal.timeout(30000) });
if (![502, 503, 504].includes(res.status)) return res;
console.log("attempt", attempt, "got", res.status);
} catch (err) {
console.log("attempt", attempt, "failed:", reason(err));
}
if (attempt < tries) await sleep(5000 * 2 ** (attempt - 1));
}
throw new Error("The proxy is still failing; check the line or contact support");
}
const res = await get("https://65proxy.com/ip.json");
console.log(await res.json());When to stop retrying and what to send support are in proxy keeps disconnecting. To change the IP from the same script, see rotating the IP with an API.
Common errors
With undici, every failure surfaces as TypeError: fetch failed; the real reason is inside err.cause, which the reason() helper above prints.
| Error (innermost message) | Cause | Fix |
|---|---|---|
invalid onRequestStart method |
Built-in fetch with a ProxyAgent from a different undici version |
Import fetch from undici, or use setGlobalDispatcher |
Proxy response (407) !== 200 when HTTP Tunneling |
Wrong username or password, or unencoded special characters | Copy the login again; see 407 errors |
Proxy response (502) !== 200 when HTTP Tunneling |
The proxy can't reach the site, for example an IPv6-only address | See tunnel errors |
ECONNREFUSED |
Wrong host or port | Check the address and port |
ECONNRESET or socket hang up now and then |
An idle connection was closed, or the line dropped | Retry, as in the code above |
| HTTPS sites fail only in axios | axios older than 1.16.1 | Upgrade, or use HttpsProxyAgent with proxy: false |
ERR_REQUIRE_ESM |
require() on an ESM-only package such as got |
Use import in a .mjs file |
When a script fails, try the same proxy with curl: if curl works, the problem is in the code. The curl commands are in using a proxy with curl.
Node.js with 65Proxy's Singapore 4G proxies
Every 65Proxy proxy has an HTTP port and a SOCKS5 port with one username and password, a rotation link, and a Singapore IP from the Singtel or M1 4G network. It is not shared with other customers.
- Plans: 1 day $4, 7 days $13, 1 month $32, plus monthly plans with more bandwidth (500GB $40, 1TB $65).
- Test your code first on the free 1-hour trial.
- Buy: get a Singapore 4G proxy; it is delivered automatically once paid.
Need a browser rather than plain requests? See Puppeteer proxy setup or Playwright proxy setup.
Frequently asked questions
Does Node's fetch use HTTP_PROXY automatically?
Not by default. Node reads HTTP_PROXY and HTTPS_PROXY only when you set NODE_USE_ENV_PROXY=1 or pass --use-env-proxy, and the feature is still experimental.
Which client is fastest through a proxy?
The difference between clients is tiny next to the network itself. Pick the one your project already uses; what really affects speed is in proxy speed.
Can I use the SOCKS5 port with fetch?
undici's experimental Socks5ProxyAgent can do it. For production code, socks-proxy-agent with https, axios or got is the more established path, or simply use the HTTP port with ProxyAgent.
How do I use a different proxy per request?
Create one ProxyAgent per proxy and pass the right one as dispatcher on each fetch call. Reuse the agents instead of creating a new one for every request.