Back to Blog
Guides
Suciu DanLast updated on May 1, 202610 min read

How to Set Up Axios Proxy in Node.js: Auth, Rotation, SOCKS5

How to Set Up Axios Proxy in Node.js: Auth, Rotation, SOCKS5
TL;DR: Axios routes requests through a proxy by accepting a proxy object with host, port, and optional auth fields. This guide covers how to set up Axios proxy configuration from scratch: basic wiring, authenticated proxies, HTTPS tunneling, a rotation system using interceptors, SOCKS5 via socks-proxy-agent, and diagnosing common errors. Every snippet is copy-pasteable Node.js code.

If you need to route HTTP traffic through an intermediary server in Node.js, understanding how to set up Axios proxy configuration correctly is the first hurdle. Axios is one of the most widely used HTTP clients in the Node.js ecosystem, offering promise-based requests and a clean config API. Unlike many other HTTP libraries, it exposes a dedicated proxy object in its request config rather than relying on environment variables or URL-string hacks.

This article is not a "what is a proxy" primer. You already know what proxies do. Instead, we jump straight into Axios-specific implementation: the minimal three-line Node.js proxy setup, authenticated proxies, HTTPS tunneling mechanics, a production-grade rotation pattern using interceptors, SOCKS5 proxy support, selective proxy bypass, and a troubleshooting reference. Every Axios proxy example here targets Node.js and is designed to run as-is after an npm install.

Quick-Start: Minimal Axios Proxy in Three Lines

The fastest path to a working Axios HTTP proxy is passing a proxy object directly into a GET request. Here is the absolute minimum you need:

const axios = require('axios');

axios.get('https://httpbin.org/ip', {
  proxy: { host: '123.45.67.89', port: 8080 }
}).then(res => console.log(res.data));

Run node app.js and check the returned origin field. If it shows the proxy's IP instead of your machine's real address, the configuration is working. That single proxy key is what separates a direct request from a proxied one, and everything else in this guide on how to set up Axios proxy connections builds on top of it.

How to Set Up Axios Proxy Configuration

The proxy field in an Axios request config accepts several properties: host (string, required), port (number, required), protocol (defaults to http), and an optional auth sub-object we cover in the next section. Unlike libraries that parse a proxy URL string, Axios keeps these as discrete fields, which makes programmatic Axios proxy configuration straightforward.

Per-Request vs Instance-Level Configuration

You have two ways to wire up a proxy in Axios Node.js projects: inline on every call, or baked into a reusable instance via axios.create().

Approach

When to use

Example scenario

Per-request (axios.get(url, { proxy }))

You rotate proxies on every request or need different proxies for different endpoints

Scraping multiple geo-restricted sites

Instance-level (axios.create({ proxy }))

One proxy for the entire session, or you want a clean default that individual calls can override

Corporate forward proxy, staging environment

An instance-level proxy still allows per-request overrides. If you pass proxy in an individual call's config, it takes precedence over the instance default. To disable the proxy for a specific call on an instance that has one, pass proxy: false explicitly. This per-request flexibility is one of the things that makes learning how to set up Axios proxy patterns valuable.

Adding Proxy Authentication

Most commercial proxies require credentials. Axios handles this through an auth object nested inside proxy, making Axios proxy authentication simple:

const axios = require('axios');

const client = axios.create({
  proxy: {
    host: process.env.PROXY_HOST,
    port: Number(process.env.PROXY_PORT),
    auth: {
      username: process.env.PROXY_USER,
      password: process.env.PROXY_PASS
    }
  }
});

client.get('https://httpbin.org/ip')
  .then(res => console.log(res.data))
  .catch(err => console.error(err.message));

A few practical notes:

  • Store credentials in environment variables, not in source code. A .env file loaded with dotenv works well during development.
  • Special characters in passwords (like @, #, or %) are safe inside the auth object because Axios does not URL-encode them the way a proxy URL string would. This is one advantage of the structured config approach.
  • If your proxy rejects the credentials, you will receive a 407 Proxy Authentication Required status. Double-check the username and password, and confirm your proxy provider has not expired the credentials.

HTTPS Proxies and the CONNECT Tunnel

When your target URL is HTTPS, Axios does not forward the request through the proxy in plain text. Instead, it issues an HTTP CONNECT request to the proxy, asking it to open a raw TCP tunnel to the destination. Once the tunnel is established, the TLS handshake happens end-to-end between your Node.js process and the target server. The proxy relays encrypted bytes without being able to read or modify them.

This matters for two reasons. First, your scraped data stays confidential even if the proxy is operated by a third party. Second, the target site sees a legitimate TLS connection, so your requests appear more natural compared to plain HTTP. Axios handles this tunneling automatically when you configure a proxy for an HTTPS target URL (see Node.js HTTPS documentation), so there is no extra code on your end. Just be aware that the proxy itself only needs to support the CONNECT method, which virtually all modern HTTP proxies do.

Building a Proxy Rotation System

A single proxy IP will get flagged quickly if you send hundreds of requests to the same site. Rotating proxies spread your traffic across multiple IPs so the target sees what looks like many different visitors. Building a proxy pool in Axios Node.js projects requires a pool class and some dead-proxy handling.

Here is a minimal round-robin pool that tracks failed proxies:

class ProxyPool {
  constructor(proxies) {
    this.proxies = proxies.map(p => ({ ...p, alive: true }));
    this.index = 0;
  }

  next() {
    const alive = this.proxies.filter(p => p.alive);
    if (!alive.length) throw new Error('All proxies dead');
    const proxy = alive[this.index % alive.length];
    this.index++;
    return { host: proxy.host, port: proxy.port, auth: proxy.auth };
  }

  markDead(host, port) {
    const p = this.proxies.find(
      px => px.host === host && px.port === port
    );
    if (p) p.alive = false;
  }
}

Use the pool with Axios like this:

const pool = new ProxyPool([
  { host: '1.2.3.4', port: 8080, auth: { username: 'u1', password: 'p1' } },
  { host: '5.6.7.8', port: 8080, auth: { username: 'u2', password: 'p2' } },
  { host: '9.10.11.12', port: 3128 }
]);

async function fetchWithRotation(url) {
  const proxy = pool.next();
  try {
    const res = await axios.get(url, { proxy, timeout: 10000 });
    return res.data;
  } catch (err) {
    pool.markDead(proxy.host, proxy.port);
    return fetchWithRotation(url); // retry with next proxy
  }
}

Setting a timeout (in milliseconds) is critical. Some proxies hang indefinitely instead of returning an error, and without a timeout your script will stall. Ten seconds is a reasonable starting point for most scraping workloads. If you want to learn more about avoiding blocks during scraping, tips on preventing IP bans are worth reviewing.

Auto-Switching Proxies with Axios Interceptors

The rotation logic above lives in the calling function. A cleaner pattern uses Axios response interceptors to auto-switch proxies when the target returns a 403 or 429, removing manual retry code from every call site:

const client = axios.create({ timeout: 10000 });

client.interceptors.request.use(config => {
  config.proxy = pool.next();
  return config;
});

client.interceptors.response.use(
  response => response,
  async error => {
    const { config } = error;
    const status = error.response?.status;
    if ((status === 403 || status === 429) && !config._retried) {
      config._retried = true;
      pool.markDead(config.proxy.host, config.proxy.port);
      config.proxy = pool.next();
      return client.request(config);
    }
    return Promise.reject(error);
  }
);

The request interceptor assigns a fresh proxy before every outgoing call. The response interceptor catches block signals and retries with a different IP once per request (the _retried flag prevents infinite loops). This interceptor-based approach is a powerful Axios proxy example for production systems, and you can swap the rotation strategy without touching any call sites.

Using SOCKS5 Proxies with Axios

Axios's built-in proxy option only supports HTTP and HTTPS proxies. If you need a SOCKS5 proxy with Axios (which operates at a lower network layer and supports UDP as well as TCP), you need the socks-proxy-agent package.

Install it alongside Axios:

npm install axios socks-proxy-agent

Then create an agent and pass it via httpAgent and httpsAgent:

const axios = require('axios');
const { SocksProxyAgent } = require('socks-proxy-agent');

const agent = new SocksProxyAgent('socks5://user:pass@127.0.0.1:1080');

axios.get('https://httpbin.org/ip', {
  httpAgent: agent,
  httpsAgent: agent,
  proxy: false  // disable built-in proxy so the agent handles routing
})
.then(res => console.log('SOCKS5 IP:', res.data.origin))
.catch(err => console.error(err.message));

Note the proxy: false on line 8. This is essential when wiring up a SOCKS5 proxy with Axios. If you leave the built-in proxy enabled alongside a custom agent, they will conflict. Setting proxy: false tells Axios to hand off all connection routing to your SOCKS agent.

Environment Variables and Selective Bypass

A common gotcha when learning how to set up Axios proxy connections: Axios does not automatically read HTTP_PROXY or HTTPS_PROXY environment variables the way tools like curl do. If you set those variables and expect Axios to pick them up, nothing will happen. You need to read them yourself and inject them into the config:

const proxy = process.env.HTTP_PROXY
  ? { host: new URL(process.env.HTTP_PROXY).hostname,
      port: Number(new URL(process.env.HTTP_PROXY).port) }
  : undefined;

const res = await axios.get('https://example.com', { proxy });

To disable the proxy selectively for certain requests (for example, calls to internal APIs that should not leave your network), pass proxy: false on those individual requests. This is useful when you have an instance-level proxy set via axios.create() but need to bypass it for health checks, calls to localhost, or requests to public developer APIs where a proxy just adds latency without providing any benefit.

When Plain Proxies Are Not Enough

Swapping IP addresses gets you past the simplest rate limits, but sophisticated anti-bot systems look at much more than your source IP. According to industry research, modern bot-detection platforms reportedly analyze request timing patterns, TLS fingerprints, header consistency, and behavioral signals like mouse movements or scroll depth. Simply rotating through a list of datacenter IPs will not fool these systems.

If you have already learned how to set up Axios proxy rotation and are still getting blocked, consider these additional layers:

  • Realistic HTTP headers: rotate User-Agent strings and include headers like Accept-Language and Referer that a real browser would send. Using Axios headers strategically helps avoid detection.
  • TLS fingerprint diversity: Node.js produces a distinctive TLS fingerprint. Tools that emulate browser TLS behavior can reduce your detection surface.
  • Residential proxy networks: these route traffic through real household IPs, making requests virtually indistinguishable from regular user traffic. They cost more than datacenter proxies but are far more effective against aggressive detection.

Troubleshooting Common Proxy Errors

Even a correct Axios proxy configuration can fail at runtime. Here are the errors you will encounter most often and what to do about them:

  • ECONNREFUSED: Axios cannot reach the proxy at all. Verify the host and port values, confirm the proxy server is running, and check that no firewall is blocking the connection.
  • 407 Proxy Authentication Required: The proxy rejected your credentials. Confirm your auth.username and auth.password are correct, and check whether your provider has rotated or expired the credentials.
  • Timeouts and hanging requests: Some proxies accept the connection but never respond. Always set a timeout value in your Axios config so your script fails fast. Understanding proxy status errors in depth can save you hours of debugging.
  • VPN conflicts: Running a VPN while also routing through a proxy can cause unexpected behavior, including traffic going through the wrong path or connections failing entirely. Adding a proxy on top of a VPN is typically redundant unless you specifically need IP rotation in a different geography.
  • X-Forwarded-For leaking your real IP: Some proxies append your original IP to this header. Elite or high-anonymity proxies strip it, so check your proxy's anonymity level if IP concealment matters.

Key Takeaways

  • The simplest way to set up an Axios proxy is passing a proxy object with host and port into any request config. Authentication adds an auth sub-object with username and password.
  • Use axios.create() for a session-wide proxy, and override with per-request proxy or proxy: false when you need flexibility.
  • For production scraping, build a proxy pool and wire it into Axios interceptors so retry logic stays out of your business code.
  • SOCKS5 proxies require socks-proxy-agent passed via httpAgent/httpsAgent, with the built-in proxy set to false.
  • Always set a timeout on proxied requests. Hanging proxies will silently stall your entire pipeline.

FAQ

Does Axios support SOCKS5 proxies natively?

No. The built-in proxy config object only handles HTTP and HTTPS proxies. For SOCKS5, install the socks-proxy-agent package and pass the resulting agent to httpAgent and httpsAgent in the request config. Set proxy: false to prevent conflicts with the built-in proxy handler.

How do I disable the proxy for a single Axios request?

Pass proxy: false in the request config for that specific call. This overrides any instance-level proxy set via axios.create(). It is useful for requests to internal services or localhost endpoints that should not route through the proxy.

Why does Axios ignore my proxy settings when environment variables are set?

Axios does not automatically read HTTP_PROXY or HTTPS_PROXY environment variables. You must parse them yourself in Node.js using new URL(process.env.HTTP_PROXY) and inject the resulting host and port into the proxy config manually.

What is the difference between residential and datacenter proxies for scraping?

Datacenter proxies use IPs from cloud providers. They are fast, affordable, and available in bulk, but their IP ranges are well-known and easier for websites to block. Residential proxies use IPs assigned by ISPs to real households, making them harder to detect but more expensive and slower.

How can I test whether my Axios request is actually going through the proxy?

Send a GET request to https://httpbin.org/ip through your configured proxy. Compare the origin field in the response to your machine's real IP address. If they differ, the proxy is active. For deeper verification, check https://httpbin.org/headers to confirm the request headers match expectations.

Conclusion

Knowing how to set up Axios proxy connections properly starts simple (three config fields) but gets nuanced once you factor in authentication, HTTPS tunneling, rotation logic, SOCKS5 support, and error handling. The patterns in this guide cover everything from quick experiments to production-ready scraping pipelines.

The most important takeaway: proxy configuration is only half the battle. You also need reliable proxies, sensible timeouts, and retry logic that does not hammer a dead endpoint. Get those fundamentals right, and your Axios-based scraper will be far more resilient.

If managing proxy pools, rotation, and anti-bot evasion is consuming more engineering time than the actual data extraction, WebScrapingAPI handles proxy rotation, CAPTCHA solving, and retry logic behind a single endpoint, letting you keep your Axios code and focus on what you do with the data.

About the Author
Suciu Dan, Co-founder @ WebScrapingAPI
Suciu DanCo-founder

Suciu Dan is the co-founder of WebScrapingAPI and writes practical, developer-focused guides on Python web scraping, Ruby web scraping, and proxy infrastructure.

Start Building

Ready to Scale Your Data Collection?

Join 2,000+ companies using WebScrapingAPI to extract web data at enterprise scale with zero infrastructure overhead.