Our stake is direct: we are Geonode and we sell proxies, so this is a guide to using our kind of product. The most useful thing in it costs nothing — verify the exit address after configuring, every time. A proxy setting that does not take effect produces no error, no warning and no failed request. It produces a working request that went straight to the target, and people run in that state for weeks. The verification section is short and it is the part to read even if you skip everything else.
Note also that axios only supports proxies in Node. In a browser it uses XMLHttpRequest and has no ability to set one; the proxy option is silently ignored.
The proxy Config Option
The built-in approach, and the right default.
import axios from "axios";
const res = await axios.get("https://api.example.com/items", {
proxy: {
protocol: "http",
host: "proxy.example.com",
port: 9000,
auth: {
username: "myuser",
password: "mypass",
},
},
});
The axios documentation documents the shape with protocol, host, hostname, port and an auth object containing username and password. One detail worth knowing: "hostname" takes precedence over "host" if both are defined, which is a quiet way to configure one thing and use another if you set both by accident.
Two points about the fields.
protocol is how you reach the proxy, not how you reach the target. For an ordinary HTTP proxy handling HTTPS traffic through a CONNECT tunnel, protocol is "http" even though your request URL is https://. Setting it to "https" means TLS to the proxy itself, which most proxies do not offer.
auth is a structured object, not a header and not part of a URL. This is a genuine convenience — you avoid the percent-encoding problem that bites people whose password contains @, : or /.
To apply it to every request, set it on an instance:
const client = axios.create({
baseURL: "https://api.example.com",
proxy: { protocol: "http", host: "proxy.example.com", port: 9000,
auth: { username: "myuser", password: "mypass" } },
timeout: 30000,
});
Environment Variables
Axios honours the conventional variables, which distinguishes it from Node's built-in fetch.
The documentation states that "you can also define your proxy using the conventional http_proxy and https_proxy environment variables", and that "you can also define a no_proxy environment variable as a comma-separated list of domains that should not be proxied".
export http_proxy=http://myuser:mypass@proxy.example.com:9000
export https_proxy=http://myuser:mypass@proxy.example.com:9000
export no_proxy=localhost,127.0.0.1,.internal
This is the approach for containerised deployments and CI, where the proxy is an environment concern rather than an application one — no code change, and the same configuration applies to every tool in the container that honours the convention.
Three practical notes.
Use lowercase. There is a specific hazard with uppercase HTTP_PROXY in CGI-like environments, where request headers become uppercase environment variables and a client honouring it can be steered by an attacker-supplied Proxy: header. Lowercase avoids the question.
no_proxy needs no spaces after commas. A leading space becomes part of the hostname and the entry silently fails to match. This is the most common no_proxy bug in any language.
Percent-encode special characters in the password. Credentials in a URL are subject to URL parsing, so p@ss splits in the wrong place. The proxy config object avoids this entirely, which is a reason to prefer it where you can.
To ignore the environment for a particular request, the documentation is explicit: "Use false to disable proxies, ignoring environment variables."
const res = await axios.get(url, { proxy: false });
That is genuinely useful — a health check against an internal service, or one request that must not be routed, without unsetting anything globally.
Custom Agents
The third route, and the one to reach for when the built-in option is not enough.
import axios from "axios";
import { HttpsProxyAgent } from "https-proxy-agent";
const agent = new HttpsProxyAgent("http://myuser:mypass@proxy.example.com:9000");
const res = await axios.get("https://api.example.com/items", {
httpsAgent: agent,
proxy: false,
});
The proxy: false matters. Without it you may have two proxy mechanisms configured simultaneously, and which one applies is not something you want to be uncertain about. Disabling the built-in option makes the agent unambiguously responsible.
The documentation describes httpAgent and httpsAgent as allowing "options to be added like keepAlive that are not enabled by default", which points at the main reason to use them:
Connection reuse. Keep-alive across requests is a substantial performance difference for anything making many calls to the same host, and it is not on by default.
SOCKS support. The built-in proxy option handles HTTP proxies. For SOCKS you need an agent from a package designed for it.
Per-agent pooling. Different agents for different targets, with independent connection pools.
The trade-off is a dependency and slightly more to reason about. For a single HTTP proxy with straightforward requirements, the built-in option is simpler and does the job.
Verify It Actually Worked
The section that matters most, and the one people skip.
const res = await axios.get("https://api.ipify.org?format=json", {
proxy: { protocol: "http", host: "proxy.example.com", port: 9000,
auth: { username: "u", password: "p" } },
});
console.log(res.data);
Run it with the proxy configured and without. If the address does not change, the proxy is not in the path. There is no error, no warning, and no failed request to alert you — this check is the only thing standing between a working configuration and a silently bypassed one.
Three reasons a configuration commonly does nothing:
Precedence. A proxy option on the request overrides the instance; proxy: false overrides the environment; and an agent may take over entirely. Configure in one place and be sure which.
no_proxy matching. An entry that unintentionally covers your target, or a stray space after a comma.
An agent already set elsewhere. If a httpsAgent is configured on the instance without proxy support, it handles the connection and the proxy option is bypassed.
For geo-targeted proxies, address checking is not enough. Verify by outcome — request something that genuinely differs by region and confirm it changed. A lookup reporting the right country while your API returns your home region's data means the targeting is not landing where it matters, which is the silent-failure pattern we wrote about in why testing proxies matters.
Timeouts and Errors Through a Proxy
Two adjustments worth making before you conclude anything is broken.
Raise the timeout. Axios has no default timeout at all, so set one — and set it from measurement rather than habit. Residential proxies add real per-request latency, which is physics rather than a fault, and a value tuned against a direct connection will produce failures that look like a broken proxy.
const client = axios.create({ timeout: 30000, proxy: { /* ... */ } });
Read the status correctly. Unlike fetch, axios rejects on HTTP error statuses by default, so a 407 arrives as a thrown error with err.response.status. Distinguish the two authentication failures:
try {
await client.get("/items");
} catch (err) {
const status = err.response?.status;
if (status === 407) throw new Error("Proxy rejected credentials");
if (status === 401) throw new Error("Target requires authentication");
if (!err.response) throw new Error(`Network error: ${err.code} ${err.message}`);
throw err;
}
A 407 means the proxy stopped you and the target was never reached. A 401 means the proxy worked and the target wants credentials — entirely different fixes. And an error with no err.response means no HTTP response arrived at all, which points at the connection rather than at either party's authentication.
Common err.code values worth branching on: ECONNREFUSED means nothing is listening at the proxy address, ETIMEDOUT means packets are being dropped somewhere, and ENOTFOUND means the proxy hostname did not resolve.
A Reusable Client Worth Copying
Assembling the pieces into something you would actually put in a project.
import axios from "axios";
const PROXY = process.env.PROXY_HOST
? {
protocol: "http",
host: process.env.PROXY_HOST,
port: Number(process.env.PROXY_PORT),
auth: process.env.PROXY_USER
? { username: process.env.PROXY_USER, password: process.env.PROXY_PASS }
: undefined,
}
: false;
export const client = axios.create({
timeout: 30000,
proxy: PROXY,
headers: { "User-Agent": "AcmeBot/1.0 (+https://acme.example.com/bot)" },
validateStatus: status => status < 500,
});
client.interceptors.response.use(
res => res,
err => {
const status = err.response?.status;
const url = err.config?.url;
if (status === 407) {
return Promise.reject(new Error(`Proxy rejected credentials for ${url}`));
}
if (!err.response) {
return Promise.reject(new Error(`Network error ${err.code} for ${url}: ${err.message}`));
}
return Promise.reject(err);
}
);
export async function verifyProxy() {
const { data } = await client.get("https://api.ipify.org?format=json");
console.log(`Exit address: ${data.ip}`);
return data.ip;
}
Five decisions in there are worth explaining.
Credentials come from the environment, and the proxy is optional. PROXY evaluates to false when no host is configured, which disables proxying explicitly rather than leaving it to whatever the environment happens to contain. That makes local development and production behave predictably, and it means no credential ever appears in source.
A timeout is set, because axios has none. Thirty seconds is a starting point to replace with a measured value once you have run through the proxy.
An honest user agent with a contact URL. It costs nothing and it is the difference between an anonymous client and one an operator can choose to allow.
validateStatus: status => status < 500 treats 4xx as a response rather than an exception, which is often what you want when a 404 is a legitimate outcome rather than a failure. Adjust to taste — the point is to decide deliberately rather than inherit the default.
The interceptor names the failure. A 407 becomes a message saying the proxy rejected the credentials; a connection failure names the error code and the URL. Both are considerably more useful in a log at three in the morning than a stack trace ending in AxiosError.
And verifyProxy() is exported and called at start-up. Running it once when the process boots turns a silent bypass into a line in your logs, which is the whole argument of this article compressed into six lines of code.
Rotating Proxies
For anything using more than one exit, a note on structure.
const proxies = [ /* ... */ ];
let i = 0;
function nextClient() {
const p = proxies[i++ % proxies.length];
return axios.create({ proxy: p, timeout: 30000 });
}
Three things worth getting right.
Rotate on failure, not on a timer. Cycling through addresses because a counter incremented wastes pool capacity and gains nothing. Rotate when a specific address stops working.
Hold one address for a session. Anything involving a sequence of related requests — a login, a multi-step flow, paginated results tied to a session — needs the same exit throughout. Requests arriving from four countries are not a session.
Track success per proxy, not in aggregate. One failing address in a pool of ten is invisible in an averaged figure and obvious in a per-address one.
Most commercial providers handle rotation at the gateway, in which case you configure one endpoint and express your preferences through the username or the port rather than managing a list yourself. That is usually less code and fewer mistakes.
Axios or Something Else
Brief, since the choice affects how much of this you need.
Axios honours the proxy environment variables, has a structured proxy option that avoids URL encoding problems, rejects on HTTP errors, and parses JSON automatically. For proxy work in Node it is the most convenient of the mainstream clients.
Node's built-in fetch does not read HTTP_PROXY at all — you must set a dispatcher explicitly with undici's ProxyAgent, and forgetting to is exactly the silent bypass described above. It also resolves on HTTP errors, so res.ok needs checking.
got and undici both handle proxies well and are worth considering for high-throughput work.
We compared the behavioural differences more fully in axios vs fetch, and the proxy handling is one of the larger practical gaps between them.
People Also Ask
How do I use a proxy with axios?
Pass a proxy object in the request or instance config with protocol, host, port and an optional auth object containing username and password. Set protocol to "http" for an ordinary HTTP proxy, even when the target URL is https://.
Does axios respect HTTP_PROXY environment variables?
Yes, in Node. The documentation states you can define a proxy using the conventional http_proxy and https_proxy variables, with no_proxy as a comma-separated exclusion list. This distinguishes it from Node's built-in fetch, which ignores them entirely.
How do I disable the proxy for one request?
Set proxy: false, which the documentation describes as disabling proxies and ignoring environment variables. This is the right way to exclude a single request without unsetting anything globally.
Why is my axios proxy not working?
Most often precedence — a request-level setting overriding an instance one, a no_proxy entry matching your target, or an agent configured elsewhere taking over. Verify by requesting a service that reports your address, because a bypassed proxy produces no error at all.
Do I need https-proxy-agent with axios?
Not for a standard HTTP proxy — the built-in proxy option handles HTTPS targets through a CONNECT tunnel. You need an agent for SOCKS proxies, for connection keep-alive, or for per-agent pooling. When you use one, set proxy: false so the two mechanisms do not compete.
How do I handle proxy authentication errors in axios?
Axios rejects on HTTP error statuses, so catch the error and read err.response.status. A 407 means the proxy rejected your credentials; a 401 means the proxy worked and the target wants credentials. An error with no err.response means no HTTP response arrived at all.
Can I use axios with a proxy in the browser?
No. Axios uses XMLHttpRequest in browsers and cannot set a proxy — the option is silently ignored. Proxy support is Node-only, which is a common source of confusion in code shared between the two.
Should I use environment variables or the config option?
Environment variables for containerised and CI deployments, where the proxy is an environment concern and the same configuration serves every tool. The config object for application-level control, and because its structured auth field avoids percent-encoding problems with special characters in passwords.
Wrapping Up
Axios handles proxies more gracefully than most Node clients: a structured config object that sidesteps URL encoding, the conventional environment variables honoured, and proxy: false as a clean escape hatch. For most work, the built-in option is all you need.
Reach for an agent when you need SOCKS, connection keep-alive, or independent pooling — and when you do, set proxy: false alongside it so there is no ambiguity about which mechanism is in charge.
Then set a timeout, because axios has none by default and residential proxies add real latency that will otherwise look like a fault. And branch on err.response?.status rather than treating every failure alike, since 407 and 401 come from different parties and have different fixes.
Above all, verify. A proxy configuration that quietly does nothing is indistinguishable from one that works — the requests succeed either way — and one line requesting a service that reports your address is the entire difference between knowing and assuming.