Axios Proxy: HTTP, HTTPS, SOCKS5, Auth and Rotation
Working axios proxy code for Node.js: the proxy option, https-proxy-agent with proxy false, SOCKS5, env vars, rotation, sticky sessions and error fixes.
To send axios requests through a proxy in Node.js, pass a proxy object with the proxy's protocol, host, port and credentials. On axios 1.16.1 and later, the same object covers http:// and https:// targets:
import axios from "axios";
// Paste the proxy URL once and let URL split it into the fields axios wants.
const proxyUrl = new URL("http://USERNAME:PASSWORD@HOST:PORT");
const client = axios.create({
proxy: {
protocol: "http",
host: proxyUrl.hostname,
port: Number(proxyUrl.port),
auth: {
username: decodeURIComponent(proxyUrl.username),
password: decodeURIComponent(proxyUrl.password),
},
},
timeout: 30_000,
});
const { data } = await client.get("https://api.ipify.org?format=json");
console.log(data.ip);It prints the proxy's exit address. If it prints your own address, the proxy was not applied.
What you need: Node.js 20 or later, npm install axios, and a proxy URL. The samples use import and top-level await, so save them as .mjs files or set "type": "module" in package.json. On Node4, copy the URL from the Connect card on the dashboard's Proxies page. A free account runs every HTTP example on this page: it includes 3 shared datacenter proxies and 1 GB of traffic a month. SOCKS5 and the rotating gateways need a paid plan, noted where they appear. Every sample here was run with axios 1.21.1, https-proxy-agent 9.1.0, http-proxy-agent 9.1.0 and socks-proxy-agent 10.1.0 on Node 24.
| You want to | Use |
|---|---|
| Proxy requests with no extra package | proxy: { protocol, host, port, auth }, with axios 1.16.1 or later for https:// targets |
| Reuse connections, cap sockets, or run an older axios | https-proxy-agent and http-proxy-agent, with proxy: false |
| Use SOCKS5 | socks-proxy-agent, with proxy: false |
| Configure the proxy outside the code | HTTP_PROXY, HTTPS_PROXY and NO_PROXY |
| Get a new IP on every request | A rotating gateway, without keep-alive |
| Keep one IP for a whole task | A -session- segment in the proxy username |
| Proxy axios in a browser or React app | Not the proxy option. See the browser section |
Axios proxy with HTTPS targets: what changed in 1.16.1
The correct way to reach an https:// site through an HTTP proxy is a tunnel: the client sends CONNECT host:443 to the proxy, then runs TLS with the destination inside that tunnel. The proxy sees the hostname and relays bytes it cannot read.
For most of its history, axios's proxy option did not do that. It sent the whole request to the proxy as GET https://host/path, in plain text. We ran axios 1.15.0 against a logging proxy to confirm it: the proxy received GET https://api.ipify.org/ and no CONNECT. Depending on the proxy, the result was an error status, a request that hung, or a page the proxy fetched for you after reading your headers. That is why older guides tell you to skip the proxy option and install https-proxy-agent.
axios 1.16.1 changed the built-in path to open a CONNECT tunnel for https:// targets. With 1.21.1 the first example on this page produces one CONNECT api.ipify.org:443 at the proxy and a 200 through it.
So the decision is short:
- Check your version first:
npm ls axios. Anything below 1.16.1 needs an upgrade or the agent setup in the next section. - Choose the
proxyoption if you want the least code. It opens a new tunnel for every request and does not reuse connections, which on a rotating gateway also means a new exit per request. - Choose agents if you want keep-alive, a socket cap, SOCKS5, or code that behaves the same on every axios version.
Axios with https-proxy-agent, and why proxy: false
An agent takes over the connection step. axios hands it a request, the agent connects to the proxy, opens the tunnel, and gives back a socket.
npm install axios https-proxy-agent http-proxy-agentimport axios from "axios";
import { HttpProxyAgent } from "http-proxy-agent";
import { HttpsProxyAgent } from "https-proxy-agent";
const proxyUrl = "http://USERNAME:PASSWORD@HOST:PORT";
const agentOptions = { keepAlive: true, maxSockets: 20 };
const client = axios.create({
proxy: false,
httpAgent: new HttpProxyAgent(proxyUrl, agentOptions),
httpsAgent: new HttpsProxyAgent(proxyUrl, agentOptions),
timeout: 30_000,
});
const first = await client.get("https://api.ipify.org");
const second = await client.get("https://api.ipify.org");
console.log(first.data, second.data);Both requests print the same address, because keepAlive: true sends the second one down the tunnel the first one opened. Three rules make this setup dependable:
Set proxy: false whenever you set an agent. axios also reads proxy settings from the environment. With HTTPS_PROXY set and proxy: false missing, axios 1.21.1 ignored the agent we passed and connected through the environment's proxy with the environment's credentials. The request succeeded, through the wrong proxy. You cannot see the environment your code will run in later, so turn that path off in code.
Fill both agent slots. httpAgent serves http:// URLs and httpsAgent serves https:// URLs. axios follows redirects, and a redirect can change scheme. With only httpsAgent set, an https:// page that redirected to http:// was fetched directly from our own address, with no error.
The packages are named for the target, not the proxy. https-proxy-agent reaches https:// destinations and http-proxy-agent reaches http:// destinations. Both take a proxy URL that starts with http://, because the hop to the proxy is plain HTTP. Writing https:// in the proxy URL makes the agent start TLS with a listener that answers in plain text, and the request dies with EPROTO and "packet length too long".
https-proxy-agent versions and import syntax
The import line is where copied snippets break, because it changed between major versions:
| Version | Import | Module format |
|---|---|---|
| https-proxy-agent 9 (current) | import { HttpsProxyAgent } from "https-proxy-agent" | ES module, Node 20 or later |
| 8 | import { HttpsProxyAgent } from "https-proxy-agent" | ES module |
| 7 | const { HttpsProxyAgent } = require("https-proxy-agent"), or the named import | CommonJS |
| 5 and older | const HttpsProxyAgent = require("https-proxy-agent") | CommonJS, default export |
http-proxy-agent and socks-proxy-agent follow the same pattern: named exports, and ES modules in their current majors. In a CommonJS project, require() loads the current versions on Node releases that can require ES modules (22.12 and later, or 20.19 and later on the 20 line); on older runtimes, install version 7. A default import against a current version fails at load with does not provide an export named 'default'.
Axios proxy authentication
axios turns the credentials into a Proxy-Authorization: Basic header. It sends that header on the CONNECT for https:// targets and on the request itself for http:// targets.
- In the
proxyobject, passauth: { username, password }as plain strings. No encoding is needed. - In an agent's proxy URL, percent-encode each half, or a password containing
@,:,/or#breaks the URL:
import axios from "axios";
import { HttpsProxyAgent } from "https-proxy-agent";
const username = encodeURIComponent("USERNAME");
const password = encodeURIComponent("PASSWORD");
const httpsAgent = new HttpsProxyAgent(`http://${username}:${password}@HOST:PORT`);
const { data } = await axios.get("https://api.ipify.org", { proxy: false, httpsAgent });
console.log(data);Two settings look like proxy authentication and are not. The top-level auth option sends credentials to the destination site. A Proxy-Authorization entry in headers travels inside the tunnel to the destination on https:// requests, and the CONNECT goes out without credentials.
Wrong credentials come back as a rejected promise whose error.response.status is 407, on both the proxy option and the agents. Fixing 407 Proxy Authentication Required works through the causes in order.
On Node4, one credential works on every product your account has an active plan for. The alternative is IP whitelisting under Auth & IP Access in Account Settings: register your address, then drop USERNAME:PASSWORD@ from the URL. Whitelisting works on every product, and a whitelisted connection is untargeted, so country and session targeting need the credential. Authentication covers both.
Axios SOCKS5 proxy
The proxy option speaks HTTP only. SOCKS5 goes through socks-proxy-agent, which performs the SOCKS handshake and hands axios a finished connection:
npm install axios socks-proxy-agentimport axios from "axios";
import { SocksProxyAgent } from "socks-proxy-agent";
const agent = new SocksProxyAgent("socks5h://USERNAME:PASSWORD@HOST:SOCKS_PORT", {
keepAlive: true,
maxSockets: 20,
});
const client = axios.create({
proxy: false,
httpAgent: agent,
httpsAgent: agent,
timeout: 30_000,
});
const { data } = await client.get("https://api.ipify.org?format=json");
console.log(data.ip);One SOCKS agent serves both slots, because SOCKS5 carries any TCP connection. The scheme decides where DNS happens:
| Scheme | Who resolves the hostname | What the proxy receives |
|---|---|---|
socks5h:// | The proxy | The hostname. Lookups happen at the exit |
socks5:// | Your machine | An IP address your resolver chose: a DNS leak, and geo-aware answers for your location instead of the exit's |
We logged both at a test SOCKS5 server: socks5h:// delivered api.ipify.org, socks5:// delivered a resolved IPv4 address. Keep the h.
Putting protocol: "socks5" in the proxy option does not work. On an http:// target axios 1.21.1 rejects with ERR_ASSERTION and "protocol mismatch". On an https:// target it sent an HTTP CONNECT to the SOCKS port, and the request sat past its timeout without settling.
On Node4, SOCKS5 uses the same host and the same credential as HTTP on a different port, shown when you switch the Connect card to SOCKS5. Every paid product has it. The free tier is HTTP(S) only. SOCKS5 proxy setup lists the per-product ports, and HTTP vs SOCKS5 helps you decide whether you need it: for ordinary web requests the destination sees the same exit address either way.
Axios proxy environment variables
With no proxy setting in code, axios in Node.js reads the standard variables:
export HTTP_PROXY="http://USERNAME:PASSWORD@HOST:PORT"
export HTTPS_PROXY="http://USERNAME:PASSWORD@HOST:PORT"
export NO_PROXY="localhost,127.0.0.1,.internal.example.com"
node app.mjsOn Windows PowerShell the form is $env:HTTPS_PROXY = "http://USERNAME:PASSWORD@HOST:PORT". Lowercase names work too, and ALL_PROXY applies when the scheme-specific variable is absent.
| In your axios config | What axios 1.21.1 does |
|---|---|
| Nothing | Uses HTTPS_PROXY for https:// URLs and HTTP_PROXY for http:// URLs. Hosts in NO_PROXY go direct |
proxy: { ... } | Uses your object and ignores the variables |
proxy: false | Ignores the variables. The request goes direct, or through the agents you set |
Agents without proxy: false | Uses the environment's proxy when a variable is set, not your agent |
Environment configuration keeps credentials out of source control. Its weakness is silence: a variable that fails to arrive produces a direct request, not an error. Pair it with the exit check at the end of this page. Node's own runtime switch for these variables, NODE_USE_ENV_PROXY, is covered in the Node.js proxy guide along with fetch, undici and got.
Rotating proxies with axios
There are two ways to change the exit between requests. Choose a rotating gateway if you want rotation without managing addresses. Choose a list if you bought specific IPs and want to decide which request uses which.
Rotation by gateway: per request or per connection
A rotating gateway is one hostname with a pool behind it. It picks an exit for each connection, so what axios does with connections decides how often the address changes:
import axios from "axios";
import { HttpProxyAgent } from "http-proxy-agent";
import { HttpsProxyAgent } from "https-proxy-agent";
const gateway = "http://USERNAME:PASSWORD@gw-rotating_datacenter.node4.io:8083";
// No keepAlive: every request opens its own tunnel and gets its own pick.
const rotating = axios.create({
proxy: false,
httpAgent: new HttpProxyAgent(gateway),
httpsAgent: new HttpsProxyAgent(gateway),
timeout: 30_000,
});
for (let i = 0; i < 3; i++) {
const { data } = await rotating.get("https://api.ipify.org");
console.log(data);
}This prints three addresses. A later pick can repeat an earlier one, so expect variety, not a strict no-repeat sequence. Counted at the proxy over three requests to one host:
| Setup | Tunnels opened | Exit |
|---|---|---|
proxy option | Three | A new pick each request |
| Agents with default options | Three | A new pick each request |
Agents with keepAlive: true | One | The same exit until the tunnel closes |
Any of them with a -session- username | One or three | The same exit for the session's lifetime |
So keep-alive and rotation pull in opposite directions. Reuse tunnels when you want speed against one host and do not care that the address stays put. Open a tunnel per request when each request should stand alone.
Sticky sessions: hold one IP with the username
To keep one address on purpose (a login, a cart, a paginated crawl), add a session id to the proxy username. Every connection carrying that id uses the same exit, with or without keep-alive:
import axios from "axios";
import { HttpProxyAgent } from "http-proxy-agent";
import { HttpsProxyAgent } from "https-proxy-agent";
function stickyClient(sessionId) {
const proxyUrl = `http://USERNAME-session-${sessionId}:PASSWORD@gw-rotating_datacenter.node4.io:8083`;
return axios.create({
proxy: false,
httpAgent: new HttpProxyAgent(proxyUrl),
httpsAgent: new HttpsProxyAgent(proxyUrl),
timeout: 30_000,
});
}
const account = stickyClient("task81f3");
console.log((await account.get("https://api.ipify.org")).data);
console.log((await account.get("https://api.ipify.org")).data);Both lines print the same address. The id is a string you invent, letters and digits. On Rotating Datacenter and Rotating Unmetered it holds its exit for up to 30 minutes from first use. Give each task its own id and its own client, so one task's cookies and exit stay together. A country segment goes before the session: USERNAME-country-us-session-task81f3. Sticky vs rotating sessions covers how long to hold a session and what to do when one expires.
Node4 sells the rotating gateway two ways, on one pool with exits in the US, Italy and Spain. Rotating Datacenter is billed per gigabyte, from $5.90/month for 10 GB ($0.59/GB). Rotating Unmetered has no byte meter and is priced by concurrent connections, from $29.00/month for 250 connections ($0.116 per connection), on gw-rotating_unmetered.node4.io port 8084. Pay by the gigabyte if you use a little, by concurrency if you use a lot: rotating pricing and unmetered pricing list every tier. The free tier does not reach the gateways.
Rotation in code: one client per proxy
With a list of static proxies, build one axios client per proxy and pick a client per request. Building them once keeps each proxy's connections warm:
import axios from "axios";
import { HttpProxyAgent } from "http-proxy-agent";
import { HttpsProxyAgent } from "https-proxy-agent";
const PROXIES = [
"http://USERNAME:PASSWORD@HOST1:PORT",
"http://USERNAME:PASSWORD@HOST2:PORT",
"http://USERNAME:PASSWORD@HOST3:PORT",
];
const clients = PROXIES.map((proxyUrl) =>
axios.create({
proxy: false,
httpAgent: new HttpProxyAgent(proxyUrl, { keepAlive: true, maxSockets: 10 }),
httpsAgent: new HttpsProxyAgent(proxyUrl, { keepAlive: true, maxSockets: 10 }),
timeout: 30_000,
}),
);
let next = 0;
async function get(url, attempts = clients.length) {
let lastError;
for (let i = 0; i < attempts; i++) {
const client = clients[next++ % clients.length];
try {
return await client.get(url);
} catch (error) {
if (error.response && error.response.status !== 407) throw error; // the target answered
lastError = error; // the proxy failed: try the next one
}
}
throw lastError;
}
console.log((await get("https://api.ipify.org")).data);A status from the target, such as a 404, is thrown straight away, so a healthy proxy is not skipped for the site's answer. When a task needs one address throughout, give it one client instead of the cycle. Shared datacenter proxies and dedicated datacenter proxies are the list products, and how to rotate proxy IPs compares the mechanisms.
Concurrency limits: cap the sockets, not the promises
Promise.all(urls.map((u) => client.get(u))) starts every request at once. Node's agents default to maxSockets: Infinity, so a thousand URLs become a thousand simultaneous tunnels. Set maxSockets on the agents and the surplus requests queue inside the agent:
import axios from "axios";
import { HttpProxyAgent } from "http-proxy-agent";
import { HttpsProxyAgent } from "https-proxy-agent";
const proxyUrl = "http://USERNAME:PASSWORD@HOST:PORT";
const limits = { keepAlive: true, maxSockets: 5 };
const httpAgent = new HttpProxyAgent(proxyUrl, limits);
const httpsAgent = new HttpsProxyAgent(proxyUrl, limits);
const client = axios.create({ proxy: false, httpAgent, httpsAgent, timeout: 60_000 });
const urls = Array.from({ length: 20 }, () => "https://api.ipify.org");
const results = await Promise.allSettled(urls.map((url) => client.get(url)));
console.log(results.filter((r) => r.status === "fulfilled").length, "of", urls.length, "succeeded");
httpAgent.destroy();
httpsAgent.destroy();Twenty requests ran through five tunnels in our test. Three details matter in production:
maxSocketscounts per destination host. A crawl across many hosts needsmaxTotalSocketsas well, which caps the agent as a whole.- Time spent queued does not count toward the axios
timeout. The timer starts when a request gets its socket: three 3-second requests through one socket all passed a 4-secondtimeout. For a deadline on the whole wait, passsignal: AbortSignal.timeout(ms). - Idle kept-alive sockets are still open connections. Call
agent.destroy()when a job ends.
That last point costs money on a connection-priced plan. Rotating Unmetered counts connections held open through the gateway, idle ones included. At the limit, the gateway refuses the next connection with a 429 and an X-Node4-Conn-Limit header, which axios exposes as error.response.headers["x-node4-conn-limit"]. Set maxTotalSockets at or below your plan's connection count and back off for a second or two before retrying. Rotating Unmetered connection limits explains what counts.
On the other products the per-plan thread figures are fair-use guidance, and the practical ceiling is what the target tolerates from one address.
Timeouts and retries through a proxy
axios has no default timeout. A proxied request can stall reaching the proxy, opening the tunnel, or waiting on the target, so set one on every client. Two forms behave differently:
| Setting | Error when it fires | What it measures |
|---|---|---|
timeout: 30_000 | ECONNABORTED, "timeout of 30000ms exceeded" | The request once it has a socket. Time queued behind maxSockets is not counted |
signal: AbortSignal.timeout(30_000) | ERR_CANCELED | Wall-clock time from the call, queue included |
For retries, repeat only what is safe to repeat and wait longer each time:
import axios from "axios";
import { HttpProxyAgent } from "http-proxy-agent";
import { HttpsProxyAgent } from "https-proxy-agent";
const proxyUrl = "http://USERNAME:PASSWORD@HOST:PORT";
const client = axios.create({
proxy: false,
httpAgent: new HttpProxyAgent(proxyUrl),
httpsAgent: new HttpsProxyAgent(proxyUrl),
timeout: 30_000,
});
const RETRY_STATUS = new Set([429, 500, 502, 503, 504]);
async function getWithRetry(url, attempts = 4) {
for (let attempt = 1; ; attempt++) {
try {
return await client.get(url);
} catch (error) {
const status = error.response?.status;
const retryable = status ? RETRY_STATUS.has(status) : error.code !== "ERR_CANCELED";
if (!retryable || attempt === attempts) throw error;
await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** (attempt - 1)));
}
}
}
const { status, data } = await getWithRetry("https://api.ipify.org");
console.log(status, data);The agents here have no keep-alive, so on a rotating gateway each retry leaves through a new tunnel and a new exit. With keepAlive: true a retry reuses the open tunnel and arrives from the address that was just refused. A 407 is not in the retry set: wrong credentials stay wrong.
Axios proxy errors and fixes
Each message below was produced on purpose against a test proxy with axios 1.21.1.
| What you see | Cause | Fix |
|---|---|---|
Request failed with status code 407 | The proxy rejected the credentials | Check username, password and encoding. See the 407 guide |
connect ECONNREFUSED with the proxy's address | Nothing accepted the connection | Check host and port against the Connect card, and your outbound firewall |
EPROTO, "packet length too long" or "wrong version number" | The proxy URL starts with https:// | Use http:// in the proxy URL |
Proxy connection ended before receiving CONNECT response | An HTTP agent is pointed at a SOCKS5 port | Use the HTTP port, or switch to socks-proxy-agent |
Received invalid Socks5 initial handshake | A SOCKS agent is pointed at an HTTP port | Use the SOCKS5 port |
Socks5 Authentication failed, or Socks5 proxy rejected connection - NotAllowed | SOCKS5 refusal: wrong credentials, a free account on the SOCKS5 port, or a Rotating Unmetered plan at its connection limit | Check credentials and plan |
ERR_ASSERTION, "protocol mismatch" | protocol: "socks5" inside the proxy option | Use socks-proxy-agent with proxy: false |
A 400, an odd response or a hang on https:// URLs only | axios older than 1.16.1 using the proxy option | Upgrade axios, or use the agents |
429 with an X-Node4-Conn-Limit header | Rotating Unmetered plan at its connection limit | Lower maxTotalSockets, close idle agents, or add capacity |
502 from a rotating gateway after adding -country- | No exits in the requested country | Check the country code. A retry will not help |
timeout of 30000ms exceeded (ECONNABORTED) | The proxy or target was slow to connect or answer | Raise the timeout, or retry on a new connection |
does not provide an export named 'default' | A default import against a current agent package | import { HttpsProxyAgent } from "https-proxy-agent" |
UNABLE_TO_VERIFY_LEAF_SIGNATURE or CERT_HAS_EXPIRED | The destination's certificate failed verification on your machine. A CONNECT proxy does not replace certificates | Check the system clock and any TLS-inspecting software. Do not disable verification |
| The request prints your own IP | The proxy is not applied: an environment variable won, an agent slot is empty, or the code runs in a browser | Set proxy: false with both agents, and run the exit check below |
A request that succeeds through the proxy and still gets a 403 or a CAPTCHA from the target is not a configuration error: the target is judging the address or the request. Why is my IP getting blocked covers that side.
Axios proxy in the browser, React and Vite
The proxy option, httpAgent and httpsAgent exist only in Node.js. In a browser, axios hands the request to the browser's own network stack, which uses the system or browser proxy settings and ignores all three. No error is raised.
The "proxy" in a Vite, webpack or Create React App config is a different feature with the same name. It makes the development server forward API calls to your backend so the browser sees one origin and CORS does not apply. It does not change the IP address your requests leave from, and it does not exist in a production build.
To send browser traffic through a proxy from code, drive the browser itself: Puppeteer and Playwright proxies and the browser automation proxies page cover that. For an app that calls an API through a proxy, make the call from your server with one of the Node setups above.
Verify the exit address at startup
Every mistake on this page that matters produces a request that succeeds, from the wrong address. Check the address once when the process starts:
import { isIP } from "node:net";
import axios from "axios";
import { HttpProxyAgent } from "http-proxy-agent";
import { HttpsProxyAgent } from "https-proxy-agent";
const proxyUrl = "http://USERNAME:PASSWORD@HOST:PORT";
const proxied = axios.create({
proxy: false,
httpAgent: new HttpProxyAgent(proxyUrl),
httpsAgent: new HttpsProxyAgent(proxyUrl),
timeout: 30_000,
});
const direct = axios.create({ proxy: false, timeout: 30_000 });
async function exitIp(client) {
const { data } = await client.get("https://api.ipify.org", { responseType: "text" });
const ip = String(data).trim();
if (!isIP(ip)) throw new Error(`not an IP address: ${ip.slice(0, 80)}`);
return ip;
}
const [mine, exit] = await Promise.all([exitIp(direct), exitIp(proxied)]);
if (mine === exit) throw new Error("traffic is not leaving through the proxy");
console.log("proxy exit:", exit);axios already rejects on a non-2xx status, and the isIP test rejects an error page that happens to differ from your address. The check proves the route to the echo service. It does not prove that a particular target accepts the proxy.
Runnable versions of the axios, SOCKS5 and per-request rotation samples are in the Node.js folder of our examples repository on GitHub. If you are still choosing between static addresses and a gateway, the pricing page lists every product side by side.