Axios and node fetch behind an authenticated proxy
Why the same proxy works in curl and fails in Node
A proxy works in curl, then does something strange the moment you move it into Node. The request leaves from your own IP. Or it hangs until the timeout. Or it returns a 407 even though you’re sure the password is right. I’ve watched all three happen on production scrapers, and nearly every time the cause was a small mismatch between how the proxy expects to be spoken to and how the HTTP library actually speaks.
This article is about those mismatches. It covers Axios, the fetch that ships inside modern Node, and the older node-fetch package, each behind a proxy that needs a username and password. That’s the normal shape of a paid residential, mobile or datacenter proxy: a host, a port, and credentials from a dashboard.
The scope is plumbing. It gets your requests to leave through the exit you chose, and it helps you notice when they didn’t. It doesn’t make a scraper invisible, and nothing here stops a site from rate limiting or blocking you if your traffic looks abusive or ignores what the site asks. Whether a target is fine to scrape is a question you answer before writing code: read the terms, check robots.txt, and stay away from personal data and anything behind a login or paywall you weren’t given access to.
Where I describe library behavior, I’m describing what I’ve seen on current releases, and libraries change. Axios, undici and the proxy agent packages ship fixes regularly, so run the verification step later in this piece on your own versions instead of trusting my memory or anyone’s blog post, including this one.
The plan: first what an authenticated proxy is on the wire, then each client in turn, then the operational problems that show up once you run this at volume.
What an authenticated proxy does on the wire
For plain http:// targets, the client sends the whole request to the proxy with the absolute URL on the request line, and the proxy forwards it. For https:// targets, the client first sends a CONNECT request naming the destination, such as CONNECT example.com:443. If the proxy accepts, it opens a raw TCP pipe to the destination and the client runs TLS through it. The proxy sees the hostname and the byte volume, but not the page contents, because the TLS session is between you and the site.
Authentication rides on the first message to the proxy. If credentials are missing or wrong, the proxy answers 407 Proxy Authentication Required with a Proxy-Authenticate header, usually asking for Basic. The client then sends Proxy-Authorization: Basic followed by the base64 of username:password. That’s all of it. A 401 is a different animal: it comes from the target site about the target’s own login, and mixing the two up wastes hours.
Two consequences matter for Node. First, for HTTPS targets the credentials belong on the CONNECT request, not on the request inside the tunnel. A library that puts the header on the inner request, or doesn’t tunnel at all, will misbehave on HTTPS while working fine on HTTP. Second, the connection to the proxy itself can be plain http:// or TLS. Most providers hand you a plain HTTP proxy endpoint that still tunnels HTTPS targets perfectly well. Don’t confuse the scheme of the proxy with the scheme of the target.
You can test all of this without Node. A curl call with --proxy-user against an IP echo service tells you whether the endpoint and credentials work. If curl fails, Node will fail, and you’ve saved yourself from debugging the wrong layer.
Axios and its built-in proxy option
Axios has a proxy config object:
const axios = require('axios');
const res = await axios.get('http://httpbin.org/ip', {
proxy: {
protocol: 'http',
host: 'proxy.example.com',
port: 8000,
auth: { username: process.env.PROXY_USER, password: process.env.PROXY_PASS },
},
timeout: 15000,
});
console.log(res.data);
For http:// targets this behaves as you’d expect, and axios builds the Proxy-Authorization header from the auth field. The trouble is HTTPS targets. On the axios 1.x releases I’ve used, the built-in option sends the request to the proxy as a forward-style request rather than opening a CONNECT tunnel. Some proxies tolerate that, some return errors, and some return odd responses. There’s a long-running issue thread about it in the axios repository, so check the current state for your version before relying on it for https:// work. I won’t claim it’s fixed or broken everywhere, because I haven’t tested every release and you shouldn’t assume I did.
The rule I follow: use the built-in proxy object for quick experiments against http:// endpoints, and use a real tunneling agent for anything touching HTTPS, which is nearly everything now. When you use an agent, set proxy: false in the axios config. Otherwise axios can apply its own proxy handling, including environment variables, on top of your agent, and you end up debugging two layers that both think they own the connection.
One upside of the auth field: axios builds the Basic header itself, so special characters in the password are fine. They never pass through a URL. That’s an advantage over URL-embedded credentials, which I’ll come back to.
Axios with a tunneling agent
The reliable pattern is an agent that performs the CONNECT tunnel for you. The https-proxy-agent package is the usual choice:
const axios = require('axios');
const { HttpsProxyAgent } = require('https-proxy-agent');
const user = encodeURIComponent(process.env.PROXY_USER);
const pass = encodeURIComponent(process.env.PROXY_PASS);
const agent = new HttpsProxyAgent(`http://${user}:${pass}@proxy.example.com:8000`);
const client = axios.create({
httpAgent: agent,
httpsAgent: agent,
proxy: false,
timeout: 15000,
});
const res = await client.get('https://httpbin.org/ip');
console.log(res.data);
Each line is doing real work. Both httpAgent and httpsAgent are set, because a redirect from https to http, or the reverse, would otherwise leave through your own IP. proxy: false switches off axios’s own proxy logic. And the credentials go through encodeURIComponent because they sit inside a URL, where a stray @, : or # in a password breaks parsing and often produces a 407 that looks exactly like a wrong password.
Create the agent once and reuse it through an axios instance. The agent holds the socket pool. Building a fresh one per request means a new TCP connection and a new CONNECT handshake every time, which is slow and, on metered plans, wasteful.
Mind the package version. Older releases of https-proxy-agent exported the class as the default export, while version 7 uses a named export. If you paste a snippet from an old tutorial and get “is not a constructor”, that’s why. Match the import to your lockfile.
The same agent also handles plain http:// targets. The name describes the proxy’s ability to tunnel, not the target scheme, so one agent for both is simpler than splitting.
Environment variables and NO_PROXY
Axios on Node reads HTTPS_PROXY, HTTP_PROXY and NO_PROXY when you haven’t configured a proxy yourself. So this works with zero proxy code in the script:
HTTPS_PROXY=http://user:[email protected]:8000 node scrape.js
That’s handy in containers, where you set it once in the deployment and leave the application alone. It also has costs.
First, it uses axios’s built-in proxy handling, so the HTTPS tunneling question from earlier comes back. Test it on your version.
Second, credentials now live in the process environment. On Linux, anything running as the same user can read /proc/<pid>/environ, container inspection tools show environment variables, and some crash reporters attach them to reports. An env var isn’t a hidden secret. Inject it from your secret store at start, and keep it out of compose files that get committed.
Third is NO_PROXY, and it’s the one that bites people. Your scraper probably also talks to a database, a queue, a metrics endpoint and maybe an internal API. If those requests route through a metered external proxy, you pay for the bytes, add latency, and may hand internal hostnames to a third party. List them: NO_PROXY=localhost,127.0.0.1,.internal.example.com. Wildcard and CIDR handling differs between tools, so test with a known internal host.
Uppercase and lowercase variants of these variables both exist, and different tools prefer different ones. If both are set with different values, you get surprises. Pick one style and stick with it.
Finally, Node’s built-in fetch ignores these variables by default. Recent Node releases added an opt-in, NODE_USE_ENV_PROXY=1, to make the http modules and fetch honor them, but read the docs for the exact version you run before building on it.
Built-in fetch and undici’s ProxyAgent
Node’s global fetch is powered by undici, and undici has its own proxy support through ProxyAgent. You hand it to fetch as a dispatcher:
import { ProxyAgent, fetch } from 'undici';
const token = 'Basic ' + Buffer.from(
`${process.env.PROXY_USER}:${process.env.PROXY_PASS}`
).toString('base64');
const dispatcher = new ProxyAgent({ uri: 'http://proxy.example.com:8000', token });
const res = await fetch('https://httpbin.org/ip', { dispatcher });
console.log(await res.json());
Notice that I import fetch from undici instead of using the global one. The global fetch uses the undici copy bundled inside Node, and passing a dispatcher created by a separately installed undici version can fail in confusing ways when the two versions disagree. Importing both from the same package removes that variable.
Building the token by hand also sidesteps URL encoding. The password never touches a URL, so odd characters are safe.
There’s a global alternative, setGlobalDispatcher(dispatcher), which routes every fetch in the process through the proxy. That’s convenient and dangerous in the same breath. Your calls to internal services, your own database gateway and your alerting webhook would all go through the proxy as well. For a scraper that mixes external and internal traffic, I’d pass the dispatcher per call.
Two behaviors to know. ProxyAgent uses CONNECT for HTTPS targets, which is what you want. And when the proxy rejects the tunnel, fetch throws an error whose message mentions the proxy response status, such as 407, instead of returning a normal Response. That’s different from a 403 or 429 from the target site, which arrive as ordinary responses. Also remember that fetch doesn’t reject on 4xx or 5xx, so check res.ok yourself.
The node-fetch package
The node-fetch package is older and, on modern Node, often unnecessary. You’ll still find it in legacy code, so here’s the proxy pattern. It takes an agent option, and the same tunneling agent from the Axios section plugs straight in:
import fetch from 'node-fetch';
import { HttpsProxyAgent } from 'https-proxy-agent';
const agent = new HttpsProxyAgent(proxyUrl); // credentials URL-encoded, as before
const res = await fetch('https://httpbin.org/ip', { agent });
console.log(await res.json());
A few version notes. node-fetch v3 is ESM only, while v2 works with require. If you see ERR_REQUIRE_ESM, that’s the cause, and the fix is to pin v2 or move the file to ESM. Version 3 also dropped the old timeout option, so use an AbortController or AbortSignal.timeout() instead. If you rely on timeout and upgrade, your requests will silently lose their time limit.
The agent option can also be a function that receives the parsed URL and returns an agent. That’s useful when you want different handling for http and https targets, or want to bypass the proxy for specific hosts. Returning undefined means a direct connection, so be careful with that logic. A bug there is an IP leak, not an error.
Redirects follow the same agent on each hop, which is usually what you want. If a redirect lands on a host you had excluded from proxying, make sure your function makes that decision per request and not once at startup.
If you’re starting a fresh project, I’d skip node-fetch and use undici or Axios. One fewer dependency, and the proxy story is better documented.
Credentials: encoding, storage and allowlisting
Most proxy trouble I see in support threads comes down to credentials, and most of that is encoding. A proxy password containing @, :, /, ? or # will break a URL like http://user:pass@host:port unless each part is percent-encoded. encodeURIComponent on the username and password separately fixes it. Don’t encode the whole URL. And when a provider’s dashboard shows credentials that are already percent-encoded, don’t encode them twice.
If you can avoid URLs entirely, do. The explicit auth field in Axios and the hand-built token in undici carry no parsing risk.
Storage is the boring part that matters. Keep credentials in a secret manager or an untracked env file, never in the repository, and load them at process start. Proxy URLs travel around in code: config objects, agent constructors, logged errors. Some error paths can include the full proxy URL, so assume it may appear in a stack trace and scrub logs accordingly. I’ll show a small sanitizer shortly.
Many providers offer IP allowlisting as an alternative to username and password. You register the public IP of your server, and the proxy accepts connections from it without credentials. That removes the secret from your code, which is nice. The tradeoffs are real, though. You’re tied to your egress IP, so it’s awkward on dynamic addresses, serverless platforms, or a fleet behind changing NATs. And anything else on that IP can use the proxy too.
Credentials also get rotated. Build your client so the agent is constructed from a function that reads current values, not from a constant evaluated at import time. When the password changes, you want a restart or reload to be enough, not a code edit.
SOCKS5 and where DNS gets resolved
Some providers offer SOCKS5 endpoints alongside HTTP ones. In Node the usual tool is the socks-proxy-agent package, which plugs into Axios and node-fetch the same way the HTTP agents do:
const { SocksProxyAgent } = require('socks-proxy-agent');
const agent = new SocksProxyAgent('socks5h://user:[email protected]:1080');
That trailing h in the scheme matters. With socks5://, your machine resolves the target hostname through its own resolver and sends the proxy an IP address. With socks5h://, the hostname goes to the proxy and the proxy resolves it.
Why care? Local resolution means your own DNS server sees every hostname you scrape, which may not be what you want on a shared network. It also means content delivery networks that choose an edge based on the resolver’s location can return answers that don’t match the region of your exit, so the page you get may differ from what a visitor in that region sees. For geo-sensitive testing, remote resolution is usually the more faithful setup.
HTTP proxies using CONNECT behave like the h variant: the hostname goes to the proxy, which resolves it. So this is mostly a SOCKS concern.
For fetch, check undici’s current documentation for SOCKS support before assuming it exists in your version. I’d rather pair Axios with socks-proxy-agent than guess. Also remember that SOCKS carries any TCP traffic, so the proxy has no view into HTTP semantics, which can change how a provider meters and reports your usage.
Keep-alive, rotation and sticky sessions
Here’s the failure mode that surprises people who’ve used rotating proxies. You configure a rotating gateway expecting a fresh exit IP on each request, then log the exit and see the same IP a hundred times in a row. The cause is usually keep-alive. A keep-alive agent reuses one tunnel for many requests, and rotating gateways typically change the exit per new connection, per time window, or per request depending on how the provider configured it. Reuse the tunnel and you keep the exit.
The opposite is also true. Disable keep-alive and every request opens a new CONNECT handshake, which may change the exit but costs latency and, on some plans, extra overhead.
Decide what each job needs. For independent page fetches, such as a product page here and another there, rotation per request is reasonable. For multi-step flows on a public site, like paging through results where cookies and session state matter, a sticky session is the more honest pattern. A site that sees one visitor’s cookie jump between IPs mid-flow is looking at inconsistent behavior, and consistency is what a well-run scraper should show. Providers usually implement sticky sessions through a parameter in the proxy username or a dedicated port, but the syntax is vendor specific, so read your provider’s docs and test it.
In code, that means one agent and one cookie jar per session:
const sessions = new Map();
function clientFor(sessionId) {
if (!sessions.has(sessionId)) {
const agent = new HttpsProxyAgent(urlForSession(sessionId), { keepAlive: true, maxSockets: 4 });
sessions.set(sessionId, axios.create({ httpAgent: agent, httpsAgent: agent, proxy: false }));
}
return sessions.get(sessionId);
}
maxSockets caps parallel tunnels per session, which also caps how hard you hit the target.
Timeouts, error codes and log hygiene
Axios’s timeout option is easy to misread. In Node it behaves more like an inactivity limit than a hard deadline for the whole request, so a trickling response can outlive it. For a real ceiling, add a signal:
await client.get(url, { signal: AbortSignal.timeout(20000) });
Then learn to read what comes back, because each failure points at a different layer:
ECONNREFUSEDorENOTFOUNDon the proxy host: wrong host or port, or a typo. Nothing reached the proxy.ETIMEDOUTorECONNRESET: network path, provider outage, or a firewall between you and the proxy.- A thrown tunnel error mentioning 407: the proxy rejected your credentials or your IP isn’t allowlisted.
- 502, 503 or 504 from the gateway: the proxy couldn’t reach an exit or the destination. That’s on the provider side or the exit, and worth retrying once after a pause.
- 429 or 403 from the target: the site is telling you something about your behavior. More on that shortly.
Logging is where secrets leak. An AxiosError carries config, which includes request headers and any proxy auth you set, and if you log the whole object to a file or a log service, your proxy password goes with it. Log a narrow slice instead:
function describe(err) {
return {
code: err.code,
status: err.response?.status,
message: String(err.message).replace(/\/\/[^@\s]+@/g, '//***@'),
};
}
That regex strips user:pass@ from any URL that sneaks into a message. It’s a safety net, not a substitute for keeping credentials out of places they don’t belong.
Proving the traffic really goes through the proxy
Never assume the proxy is in use because you wrote the config. Prove it. The test is cheap: ask an IP echo service for your address directly, then through the proxy, and compare.
async function exitIp(client) {
const res = await client.get('https://httpbin.org/ip', { signal: AbortSignal.timeout(15000) });
return res.data.origin;
}
const direct = await exitIp(axios.create({ proxy: false }));
const proxied = await exitIp(client);
console.log({ direct, proxied, same: direct === proxied });
If same is true, you’re leaking. Run the check for each case that matters to you, because a config can work for one path and fail for another:
- An https:// target and an http:// target.
- A URL that redirects from one scheme to the other.
- Requests made concurrently, not just one at a time.
- A request made after the agent has been idle for a while.
Two other cross-checks cost nothing. Your provider’s dashboard shows bandwidth or request counters, so send a known number of requests and see whether the counter moves by a plausible amount. And a geolocation or ASN lookup on the exit IP tells you whether you got the kind of address you paid for, such as a mobile carrier range versus a hosting range. Treat that as a sanity check rather than an audit. Lookup databases disagree with each other, and I haven’t run any test here that I can quote you results from, so run your own.
Put the exit check at the start of every scraper run. If the check fails, the job should stop before it touches the target. A scraper that quietly falls back to your real IP is worse than one that crashes.
A polite fetcher, worked through
Here’s a small fetcher that puts the pieces together for a public site where scraping is permitted. It uses one shared agent, a per-host delay, a retry policy that respects the server, and an honest User-Agent.
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
let lastHit = 0;
async function politeGet(url, { minGapMs = 2000, tries = 3 } = {}) {
for (let attempt = 1; attempt <= tries; attempt++) {
const wait = lastHit + minGapMs - Date.now();
if (wait > 0) await sleep(wait);
lastHit = Date.now();
try {
return await client.get(url, {
headers: { 'User-Agent': 'ExampleBot/1.0 (+https://example.com/bot; [email protected])' },
signal: AbortSignal.timeout(20000),
validateStatus: (s) => s < 500 && s !== 429,
});
} catch (err) {
const status = err.response?.status;
if (status === 429 || status >= 500 || !status) {
const retryAfter = Number(err.response?.headers?.['retry-after']) * 1000;
await sleep(retryAfter || 2 ** attempt * 1000);
continue;
}
throw err;
}
}
throw new Error(`gave up on ${url}`);
}
The design choices matter more than the syntax. The delay is per host, not per process, so in real use you’d keep one timestamp per hostname. The retry honors Retry-After when the server provides it, and otherwise backs off exponentially. A 403 is not retried, because hammering a door that just closed in your face is how a rate limit becomes a ban.
Notice what this does not do. It doesn’t change the User-Agent to imitate a browser, and it doesn’t rotate identities to get around a limit. The contact address in the header means a site operator who finds your traffic annoying can write to you instead of guessing. That’s not a guarantee of anything, but it’s the posture I’d defend.
What sites see, and what a proxy doesn’t change
It helps to understand, from the defender’s side, what a scraper looks like, because it explains why a proxy alone doesn’t decide the outcome. Sites and the services they hire look at several signals together: request rate per IP and per session, how consistent headers and cookies are across a session, whether the client’s TLS handshake matches what the claimed User-Agent would normally produce, how the IP is classified (hosting, residential, mobile), and whether the traffic pattern resembles a person or a loop.
A proxy changes exactly one of those: the IP. Node’s HTTP stacks still produce a TLS handshake and header set that differ from a desktop browser’s, and any site classifying clients that way can tell a script from a person. That’s not a flaw to be engineered around in a blog post. It’s a reason to lean on the compliant options first: an official API or data feed, a licensed dataset, a sitemap, or an email asking for permission. Plenty of operators will say yes to a low-volume, identified client.
Different proxy types also carry different baggage. Datacenter ranges are cheap and fast and are easy for a site to recognize as hosting. Residential and mobile ranges look more like ordinary visitors, but they cost more, often bill by the gigabyte, and come with shared-use and sourcing questions you should ask your provider about directly. None of them is risk free. Any of them can be rate limited or blocked if the traffic behind them is aggressive.
When you do get blocked, treat it as information. A 429 says slow down. A 403 on one path can mean that section is off limits to automated clients. A sudden wall of challenge pages is the site asking you to stop. Back off, reread the terms, and consider whether the data is worth pursuing at all.
What to change on Monday
If you run scrapers through an authenticated proxy in Node, here’s the short list I’d work through, in order.
- Run the exit IP check against your real client, for http, https and a redirect between them. If the exit matches your own IP anywhere, fix that before anything else.
- Stop using Axios’s built-in
proxyobject for HTTPS targets unless you’ve confirmed on your version that it tunnels correctly. Move to an agent withproxy: false. - For built-in fetch, import both
fetchandProxyAgentfrom the same undici package, and pass the dispatcher per call instead of setting a global one. - Percent-encode credentials wherever they sit in a URL, or avoid URLs by using explicit auth fields or a hand-built token.
- Add
NO_PROXYentries for every internal host your scraper talks to. - Decide on purpose whether each job needs rotation or a sticky session, then configure keep-alive and agents to match. Don’t let the default decide for you.
- Replace whole-error logging with the narrow
describepattern so proxy passwords can’t reach your logs. - Add a hard deadline with
AbortSignal.timeout, a per-host delay, and retry logic that respectsRetry-Afterand gives up on 403. - Put your contact details in the User-Agent, check robots.txt, and confirm the target data isn’t personal, paywalled or covered by terms that forbid what you’re doing.
None of this promises a scraper that never gets blocked. Sites decide that, and they can change their minds. What it gives you is a setup that fails loudly, leaks nothing, and behaves like a considerate client, which is the best position to be in when something does go wrong.
If you want more on picking proxy types, running scrapers responsibly and comparing providers based on tests that are actually shown, head to the Proxy Scraping home page and watch the companion video on the channel.
Get new guides and videos first — join the Telegram channel.