Tutorials10 min read

Node.js Proxy Setup with Axios — Complete Guide

ResProxy Team
Node.js Proxy Setup with Axios — Complete Guide

Axios is the most popular HTTP client for Node.js, and it provides built-in proxy support that makes it easy to route requests through residential or datacenter proxies. Whether you are building an API scraper, a price monitoring tool, or a data pipeline, this guide shows you how to configure proxies with Axios from basic setup to production-grade rotation.

Node.js Axios proxy setup
Node.js Axios proxy setup

Prerequisites

Install Axios in your Node.js project:

`bash npm install axios `

You need Node.js 18 or later and proxy credentials from your provider.

Basic Proxy Configuration

Axios supports proxies through its config object. Here is the simplest setup:

`javascript const axios = require("axios");

const response = await axios.get("https://httpbin.org/ip", { proxy: { protocol: "http", host: "gate.resproxy.io", port: 7777, }, });

console.log(response.data); // Output: { origin: "185.xxx.xxx.xxx" } `

The proxy config accepts protocol, host, port, and optionally auth for authenticated proxies.

Authenticated Proxy Setup

Most proxy services require username and password authentication:

`javascript const axios = require("axios");

const client = axios.create({ proxy: { protocol: "http", host: "gate.resproxy.io", port: 7777, auth: { username: "your_username", password: "your_password", }, }, timeout: 30000, });

async function checkIP() { const response = await client.get("https://httpbin.org/ip"); console.log("Proxy IP:", response.data.origin); }

checkIP(); `

Using axios.create() with the proxy config creates a reusable client instance where every request is automatically proxied.

Axios proxy authentication
Axios proxy authentication

Using https-proxy-agent for HTTPS Proxies

Axios's built-in proxy support has limitations with HTTPS targets. For production use, the https-proxy-agent package provides more reliable HTTPS proxy tunneling:

`bash npm install https-proxy-agent `

`javascript const axios = require("axios"); const { HttpsProxyAgent } = require("https-proxy-agent");

const proxyUrl = "http://username:password@gate.resproxy.io:7777"; const agent = new HttpsProxyAgent(proxyUrl);

const response = await axios.get("https://httpbin.org/ip", { httpAgent: agent, httpsAgent: agent, proxy: false, // Disable Axios built-in proxy to use the agent });

console.log(response.data); `

Setting proxy: false is critical — it tells Axios to use the agent for proxying instead of its built-in mechanism, which avoids double-proxy issues.

SOCKS5 Proxy with Axios

For SOCKS5 proxy support, use the socks-proxy-agent package:

`bash npm install socks-proxy-agent `

`javascript const axios = require("axios"); const { SocksProxyAgent } = require("socks-proxy-agent");

const agent = new SocksProxyAgent( "socks5://username:password@gate.resproxy.io:1080" );

const response = await axios.get("https://httpbin.org/ip", { httpAgent: agent, httpsAgent: agent, proxy: false, });

console.log("SOCKS5 IP:", response.data.origin); `

Rotating Proxies with Interceptors

Axios interceptors let you inject rotation logic into every request automatically:

`javascript const axios = require("axios"); const { HttpsProxyAgent } = require("https-proxy-agent");

const PROXY_USER = "your_username"; const PROXY_PASS = "your_password"; const PROXY_HOST = "gate.resproxy.io"; const PROXY_PORT = 7777;

const client = axios.create({ proxy: false, timeout: 30000 });

// Request interceptor — creates a fresh agent per request for IP rotation client.interceptors.request.use((config) => { const proxyUrl = http://${PROXY_USER}:${PROXY_PASS}@${PROXY_HOST}:${PROXY_PORT}; const agent = new HttpsProxyAgent(proxyUrl); config.httpAgent = agent; config.httpsAgent = agent; return config; });

// Response interceptor — log proxy usage client.interceptors.response.use( (response) => { console.log([${response.status}] ${response.config.url}); return response; }, (error) => { console.error(Request failed: ${error.message}); return Promise.reject(error); } );

// Every request automatically gets a rotating proxy IP async function scrapePages() { const urls = [ "https://httpbin.org/ip", "https://httpbin.org/ip", "https://httpbin.org/ip", ];

for (const url of urls) { const response = await client.get(url); console.log("IP:", response.data.origin); } }

scrapePages(); `

With ResProxy's rotating endpoint, each new agent connection receives a fresh IP, so the interceptor pattern gives you automatic rotation without managing a proxy list.

Axios proxy rotation and error handling
Axios proxy rotation and error handling

Retry Logic with Axios

Add automatic retries for failed proxy connections using axios-retry:

`bash npm install axios-retry `

`javascript const axios = require("axios"); const axiosRetry = require("axios-retry").default; const { HttpsProxyAgent } = require("https-proxy-agent");

const proxyUrl = "http://user:pass@gate.resproxy.io:7777"; const agent = new HttpsProxyAgent(proxyUrl);

const client = axios.create({ httpAgent: agent, httpsAgent: agent, proxy: false, timeout: 30000, });

axiosRetry(client, { retries: 3, retryDelay: (retryCount) => retryCount * 2000, // 2s, 4s, 6s retryCondition: (error) => { return ( axiosRetry.isNetworkOrIdempotentRequestError(error) || error.response?.status === 429 || error.response?.status === 407 || error.response?.status === 503 ); }, onRetry: (retryCount, error, config) => { console.log(Retry ${retryCount} for ${config.url}: ${error.message}); }, });

async function fetchWithRetry(url) { const response = await client.get(url); return response.data; } `

Concurrent Requests

Use Promise.all or Promise.allSettled for parallel proxied requests:

`javascript const axios = require("axios"); const { HttpsProxyAgent } = require("https-proxy-agent");

const proxyUrl = "http://user:pass@gate.resproxy.io:7777";

async function fetchAll(urls, concurrency = 5) { const results = [];

for (let i = 0; i < urls.length; i += concurrency) { const batch = urls.slice(i, i + concurrency); const promises = batch.map((url) => { const agent = new HttpsProxyAgent(proxyUrl); return axios .get(url, { httpAgent: agent, httpsAgent: agent, proxy: false, timeout: 30000 }) .then((res) => ({ url, status: res.status, data: res.data })) .catch((err) => ({ url, error: err.message })); });

const batchResults = await Promise.allSettled(promises); results.push(...batchResults.map((r) => r.value || r.reason));

// Delay between batches if (i + concurrency < urls.length) { await new Promise((r) => setTimeout(r, 1000)); } }

return results; }

// Usage const urls = Array.from({ length: 20 }, (_, i) => https://example.com/page/${i + 1}); fetchAll(urls, 5).then((results) => console.log(results)); `

This batching pattern prevents overwhelming the proxy and target server while maintaining high throughput.

Environment Variable Configuration

Configure proxy settings via environment variables for deployment flexibility:

`javascript const axios = require("axios"); const { HttpsProxyAgent } = require("https-proxy-agent");

const proxyUrl = process.env.PROXY_URL || "http://user:pass@gate.resproxy.io:7777"; const agent = new HttpsProxyAgent(proxyUrl);

const client = axios.create({ httpAgent: agent, httpsAgent: agent, proxy: false, timeout: parseInt(process.env.REQUEST_TIMEOUT || "30000"), });

module.exports = client; `

Set the environment variables in your deployment:

`bash PROXY_URL=http://user:pass@gate.resproxy.io:7777 node app.js `

TypeScript Support

Axios has excellent TypeScript support. Here is a typed proxy client:

`typescript import axios, { AxiosInstance, AxiosResponse } from "axios"; import { HttpsProxyAgent } from "https-proxy-agent";

interface ProxyConfig { host: string; port: number; username: string; password: string; }

function createProxyClient(config: ProxyConfig): AxiosInstance { const proxyUrl = http://${config.username}:${config.password}@${config.host}:${config.port}; const agent = new HttpsProxyAgent(proxyUrl);

return axios.create({ httpAgent: agent, httpsAgent: agent, proxy: false, timeout: 30000, headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", }, }); }

const client = createProxyClient({ host: "gate.resproxy.io", port: 7777, username: "your_username", password: "your_password", });

async function main(): Promise { const response: AxiosResponse = await client.get("https://httpbin.org/ip"); console.log(response.data); }

main(); `

Best Practices

  1. Use https-proxy-agent instead of Axios's built-in proxy for HTTPS targets — it is more reliable
  2. Set proxy: false when using an agent to avoid conflicts with Axios's built-in proxy handling
  3. Create a new agent per request for rotation — each connection gets a new IP from the rotating endpoint
  4. Use interceptors to centralize proxy and error handling logic
  5. Batch concurrent requests with a concurrency limit of 5-10 to avoid overwhelming proxies
  6. Set timeouts on every request — 30 seconds is a good default for proxied connections

Getting Started

Configure your ResProxy credentials by following the getting started guide, then drop the proxy agent into your existing Axios code. For rotating residential proxies that assign a fresh IP per connection, ResProxy's gateway endpoint handles rotation automatically.

For the full Axios configuration reference, see the Axios documentation. For proxy agent options, refer to the https-proxy-agent npm page.

ResProxy Team

Editorial Team

The ResProxy editorial team combines expertise in proxy technology, web scraping, network infrastructure, and online privacy to deliver actionable guides and industry insights.