Node.js proxy setup: Connecting HTTP & SOCKS5 proxies to fetch and https
This guide shows Node.js 18+ code for connecting HTTP proxies via undici ProxyAgent, SOCKS5 via socks-proxy-agent, and rotating API-fetched proxy lists.
What do I need to use proxies in Node.js?
Node.js's built-in fetch uses the undici library and doesn't read proxy settings by default. Use undici's ProxyAgent as dispatcher for HTTP proxies, and socks-proxy-agent as agent for Node's https module with SOCKS5.
The example uses IP 198.51.100.23, HTTP port 8000, SOCKS5 port 1080, username spx_user, and password spx_pass. All code is in ES module format (.mjs).
npm install undici socks-proxy-agentHow to connect HTTP proxies to fetch?
Configure ProxyAgent with proxy address and Basic auth credentials in the token option. Pass as dispatcher to undici's fetch - requests will route through the proxy. HTTPS addresses are tunneled via CONNECT.
Reusing same ProxyAgent across requests speeds up connections via reuse. Create one agent per proxy and rotate through them.
import { fetch, ProxyAgent } from "undici";
const agent = new ProxyAgent({
uri: "http://198.51.100.23:8000",
token: "Basic " + Buffer.from("spx_user:spx_pass").toString("base64"),
});
const res = await fetch("https://api.ipify.org?format=json", { dispatcher: agent });
console.log(res.status, await res.json()); // "ip" should be the proxy IPHow do I connect SOCKS5 proxies?
socks-proxy-agent is an agent used with Node’s http and https modules. Use socks5h to let the proxy resolve domain names. The example below passes the agent to https.get and collects the response body for output.
For http-based libraries like axios, setting the same agent in httpAgent/httpsAgent routes requests via SOCKS5.
import https from "node:https";
import { SocksProxyAgent } from "socks-proxy-agent";
const agent = new SocksProxyAgent("socks5h://spx_user:spx_pass@198.51.100.23:1080");
https.get("https://api.ipify.org?format=json", { agent }, (res) => {
let body = "";
res.on("data", (chunk) => (body += chunk));
res.on("end", () => console.log(res.statusCode, body));
}).on("error", (err) => console.error("request failed:", err.message));How to fetch and rotate lists via API?
Start by fetching the proxy list via API, creating agents for each proxy, and rotating agents per request. The sample code below downloads an HTTP list in ip:port:user:pass format, creates a ProxyAgent array, and retries with the next proxy on failure.
Always set AbortSignal.timeout on requests. Unresponsive requests slow overall operations.
import { fetch, ProxyAgent } from "undici";
const API = "https://socks5proxy.io/api/v1";
const KEY = "YOUR_API_KEY";
const text = await (await fetch(API + "/proxies/download?format=ip:port:user:pass&protocol=http", {
headers: { Authorization: "Bearer " + KEY },
})).text();
const agents = text.trim().split("\n").map((line) => {
const [ip, port, user, pass] = line.trim().split(":");
return new ProxyAgent({
uri: "http://" + ip + ":" + port,
token: "Basic " + Buffer.from(user + ":" + pass).toString("base64"),
});
});
let i = 0;
async function get(url, tries = 3) {
for (let t = 0; t < tries; t++) {
const dispatcher = agents[i++ % agents.length];
try {
const res = await fetch(url, { dispatcher, signal: AbortSignal.timeout(20000) });
if (res.ok) return await res.text();
} catch {
// try the next proxy
}
}
return null;
}
console.log((await get("https://example.com/"))?.length);How does code change with IP auth?
Register your Node.js server's IPv4 in the dashboard, then use just the address in ProxyAgent without the token option. SOCKS5 can also be used without credentials like socks5h://198.51.100.23:1080. No need to store passwords in environment variables or code, making deployment across multiple servers easier.
How to connect using axios?
axios operates on Node's http/https modules - set socks-proxy-agent for httpAgent/httpsAgent, and disable axios's proxy option to avoid overlap.
For HTTP proxies, axios accepts host/port/auth in proxy options, but HTTPS requires agents. The https-proxy-agent package provides similar structure for HTTP proxies.
import axios from "axios";
import { SocksProxyAgent } from "socks-proxy-agent";
const agent = new SocksProxyAgent("socks5h://spx_user:spx_pass@198.51.100.23:1080");
const client = axios.create({ httpAgent: agent, httpsAgent: agent, proxy: false, timeout: 20000 });
const { data } = await client.get("https://api.ipify.org?format=json");
console.log(data);What should I consider when sending multiple requests simultaneously?
Launching thousands of requests simultaneously with Promise.all overloads both proxies and target sites. Implement a work queue with controlled concurrency using custom functions or packages like p-limit.
Distribute concurrent connections evenly across proxies to avoid overloading single IPs. Shared plans include 500 concurrent connections - stay within this limit.
Can I apply proxies globally via environment variables?
undici’s EnvHttpProxyAgent reads HTTP_PROXY, HTTPS_PROXY, and NO_PROXY environment variables to set the proxy. Register with setGlobalDispatcher, and all fetches in that process will go through the proxy. Convenient for applying to multiple libraries that use fetch internally.
Global settings use one IP for all requests - better for country-specific tools than distributed scraping. For rotation, pass dispatchers per request.
// HTTPS_PROXY=http://spx_user:spx_pass@198.51.100.23:8000 node app.mjs
import { EnvHttpProxyAgent, setGlobalDispatcher, fetch } from "undici";
setGlobalDispatcher(new EnvHttpProxyAgent());
const res = await fetch("https://api.ipify.org");
console.log(await res.text());How do I resolve common issues?
If Node.js built-in fetch seems to ignore your dispatcher, verify you're importing fetch from the undici package. Version mismatches between built-in fetch and undici may cause agent issues - importing both fetch and ProxyAgent from the same package is most reliable.
407 response indicates authentication failure. Check if the Basic token contains your base64-encoded username:password. ECONNREFUSED often means wrong port - use HTTP port for HTTP agents and SOCKS5 port for SOCKS agents.
- fetch and ProxyAgent are in the same undici package
- 407: Verify token and registered IP
- ECONNREFUSED: HTTP Port vs SOCKS5 Port
- Time Limits for All Requests