How to Set Up an Axios Proxy: Definitive Guide

Comments: 0

Axios is a JavaScript library for sending HTTP requests that supports asynchronous data processing, response and error handling, and is easily integrated into both client applications and Node.js-based servers. In many practical scenarios, especially when dealing with a large number of requests or when access to content is limited, it often becomes necessary to set a proxy in Axios. Intermediary servers allow the client’s IP address to be changed and requests to be routed through an intermediary node. Since Axios proxy usage requires precise configuration and an understanding of connection architecture, this guide presents methods for connecting HTTP(S) and SOCKS protocols, details on authentication, agent configuration, as well as common errors and ways to fix them.

Why Use an Axios Proxy?

It is applied in the following scenarios:

  • Access to regional content — sending requests from a specific geographic region to ensure proper operation with localized resources.
  • Distributed automation — managing request flows through different IP addresses for stable data processing and minimizing failures.
  • Testing and debugging — directing traffic through an intermediary server for analyzing requests and responses.
  • Working in corporate networks — meeting internal network architecture and security requirements.

Using Axios with properly configured intermediary nodes allows these scenarios to be implemented. However, it is important to understand that the library itself is only a tool for sending HTTP requests. The ability to bypass blocks, access geo-restricted content, and manage traffic depends on:

  • the characteristics of the proxy server itself (type, protocol used, authentication availability);
  • external proxying logic (IP rotation, load balancing);
  • network infrastructure features, including routing and traffic policies.

What Types of Proxies Does Axios Support?

Axios supports the following types depending on the protocol:

  1. HTTP and HTTPS (built-in support) using the proxy parameter. For configuration, it is enough to specify:
    • IP address;
    • port;
    • username and password (if required).
  2. SOCKS (via third-party agents). The library itself does not support SOCKS protocols directly, but they can be used through third-party libraries such as socks-proxy-agent.

    For integration, you need to:

    • vCreate an instance of a proxy agent specifying the type (SOCKS4/SOCKS5) and connection parameters (IP, port, username, and password),
    • Pass the created object into Axios using the httpAgent and httpsAgent options.
    • Send the request.

Important: The library does not support SSH, FTP, Shadowsocks, or similar protocols. To use them, separate tools must be applied, or tunneling should be configured at the operating system level.

How to Set Up an Axios Proxy?

Before setting up, it is important to consider several technical aspects: which protocol will be used, whether authentication is required, and if rotation is needed. Below is a step-by-step guide for different connection methods.

Preparatory Steps

Before configuring Axios HTTP proxy, you need to properly prepare the working environment.

Note: Commands should be executed in the OS terminal (CMD, PowerShell, bash) or inside the integrated terminal of an IDE such as Visual Studio Code. Correct execution requires that the current working directory corresponds to the root folder of the project.

  1. Create a new project folder and navigate into it:
    mkdir proxy-setup-axios
    cd proxy-setup-axios
  2. Initialize a Node.js project. After executing this command, a package.json file with default parameters will appear in the project folder:
    npm init -y
  3. Install the Axios library:
    npm install axios
  4. Create the main project file:
    echo>app.js
  5. Configure the startup script. Open the package.json file with any editor and replace the content of the scripts section with:
    "scripts": {
    "start": "node app.js"
    }

    Important: The package.json file can be opened in any code editor or even Notepad. When editing, carefully follow the syntax rules: do not remove or change quotation marks, brackets, or colons, as this will result in execution errors.

  6. Test the final configuration:
    npm start

If all steps are completed correctly, the application will successfully launch even with an empty configuration file. In this case, the program will simply close without displaying any additional output. This behavior is expected and indicates that the file does not yet contain executable code, but the environment is correctly set up.

Setting Up a Static HTTP Proxy

When using a static solution, all requests are routed through the same IP address. This approach is applicable when there is no need for rotation.

To connect an Axios HTTPS proxy, use the following configuration:

axios.get(URL, {
proxy: {
protocol: 'http',
host: '82.211.7.97',
port: 59100
}
})

If the intermediary server requires authentication, add an auth block:

auth: {
username: 'proxyUser',
password: 'proxyPass'
}

A complete example with request handling to the httpbin.org service:

const axios = require('axios');

async function requestThroughProxy() {
try {
const response = await axios.get('https://httpbin.org/ip', {
proxy: {
protocol: 'http',
host: '82.211.7.97',
port: 59100,
auth: {
username: 'proxyUser',
password: 'proxyPass'
}
}
});
console.log('Proxy IP:', response.data);
} catch (error) {
console.error('Request failed:', error.message);
}
}

requestThroughProxy();

The try/catch block is used to handle possible errors during the request. In this example, the it is sent to https://httpbin.org/ip, which returns the client’s current IP address. If the proxy is unavailable or the request fails, the catch block intercepts the exception and displays an error message.

Using Axios With Proxy Lists

When multiple requests go through the same IP, the risk of being blocked by the target resource increases. To avoid this, residential proxies with IP rotation support are often used. Such solutions provide a higher level of masking and allow for even distribution of the load. In practice, this is achieved by creating a preconfigured pool of IP addresses and implementing a mechanism for random or sequential selection of proxies in the code.

Here’s an example of random IP selection using the http-proxy-agent package:

const axios = require('axios');
const HttpProxyAgent = require('http-proxy-agent');

// Proxy list with authentication
const proxyList = [
'http://user1:pass1@82.211.7.97:59100',
'http://user2:pass2@82.211.7.97:59101',
'http://user3:pass3@82.211.7.97:59102'
];

// Function to randomly select a proxy
function getRandomProxy() {
const index = Math.floor(Math.random() * proxyList.length);
return proxyList[index];
}

// Sending multiple requests with IP rotation
(async () => {
for (let i = 0; i < 5; i++) {
const proxy = getRandomProxy();
const agent = new HttpProxyAgent(proxy);

try {
const response = await axios.get('https://api.ipify.org?format=json', {
httpAgent: agent,
httpsAgent: agent,
timeout: 3000
});
console.log(`Used proxy ${proxy} -- IP:`, response.data.ip);
} catch (err) {
console.error(`Proxy ${proxy} failed:`, err.message);
}
}
})();

In this example, each request for Axios uses a randomly selected proxy address from the specified list. The service https://api.ipify.org?format=json returns the external IP, allowing verification that the connection is established correctly. In case of an error (such as an unavailable server or incorrect authentication credentials), the catch block intercepts the exception and displays an error message.

Setting Up SOCKS5 Proxy in Axios

Using a SOCKS5 is justified when bypassing network filters, working with restricted APIs, and scenarios that require transferring non-standard traffic, including DNS requests.

To work with Axios socks5 proxy, it is recommended to use the socks-proxy-agent package. This package enables support for this type of intermediary through a proxy agent that integrates seamlessly with the library.

Installing the Axios proxy agent:

npm install axios socks-proxy-agent

Axios proxy config:

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

// Intermediary server parameters
const proxy = {
host: '45.192.135.68',// IP-address
port: 50101,// Port
username: 'Username',// Username (if required)
password: 'Password'// Password(if required)
};

// Build proxy URL with authentication
const proxyUrl = `socks5://${proxy.username}:${proxy.password}@${proxy.host}:${proxy.port}`;

// Create SOCKS5 agent
const agent = new SocksProxyAgent(proxyUrl);

// Request through proxy in Axios
axios.get('https://api.ipify.org/?format=json', { httpsAgent: agent })
.then(response => {
console.log('Your IP:', response.data);
})
.catch(error => {
console.error('Connection error:', error.message);
});

Important: If the intermediary does not require authentication, you should build the proxyUrl without a username and password:

const proxyUrl = `socks5://${proxy.host}:${proxy.port}`;

How to Test HTTP(S) and SOCKS Proxies in Axios?

To check whether everything working correctly, you can send a request to a service that returns the external IP address, for example:

axios.get('https://api.ipify.org?format=json', { httpsAgent: agent })
.then(response => {
console.log('Your IP:', response.data.ip);
})
.catch(error => {
console.error('Connection error:', error.message);
});

This allows you to confirm that requests are being properly proxied.

Recommendations for Configuring Proxies in Axios

Effective use of Axios with intermediaries requires thoughtful configuration, taking into account the following key aspects:

  • Request timeouts. Proper timeout values help avoid hangs with unstable connections and allow quick switching to alternative routes.
  • Retry logic. If the primary IP is unavailable, it is important to configure retries or failover to a backup address. This helps avoid downtime.
  • Choice of protocol. HTTP/HTTPS protocols are applicable in most cases: web scraping, API requests, integrations. SOCKS5 proxies are preferred when working with non-standard traffic (including TCP streams and DNS requests), bypassing network restrictions, or when minimal packet structuring is required.
  • Error handling. The code should implement error handling for both network- and HTTP-level failures. This includes connection failures, retries with exponential backoff, and switching to alternative servers when needed.

Following these recommendations ensures stable operation of Axios proxy, even under heavy loads.

Troubleshooting

Axios proxies may fail for different reasons, mainly due to the specifics of working with proxies in Node.js, where proper configuration and protocol compatibility is crucial.

ECONNREFUSED – Connection Refused

Cause: An incorrect IP address or port is specified, the proxy server is unavailable, or the connection is being blocked at the network level by a firewall or the host system.

Solution:

  1. Verify that the IP address and port are correct.
  2. If the connection is down, contact the provider or replace it.
  3. Run a curl command to check the IP:
    curl -x http://username:password@proxy-host:port https://api.ipify.org
  4. Add a try/catch block with exception handling logic and switch to another IP in case of failure:
    try {
    await axios.get(url, { httpAgent });
    } catch (err) {
    if (err.code === 'ECONNREFUSED') {
    // Switch to another IP
    }
    }

ERR_BAD_RESPONSE or 502 Bad Gateway

Cause: The intermediary server returns an invalid response from the target resource due to:

  • overload or exceeding the limit of simultaneous connections;
  • unstable connection between the proxy and the target server;
  • traffic filtering or blocking (e.g., due to anti-bot protection, geofiltering, or header restrictions).

Solution:

  • Test the problematic IP manually using curl or a similar tool to verify if it really returns an error.
  • If the error persists, temporarily remove this IP address from the pool.
  • Ensure the list includes backup addresses and configure an automatic failover/retry mechanism.
  • Use the axios-retry library, which adds retry attempts with gradually increasing intervals between them.

Tunneling socket could not be established

Cause: The intermediary server uses SOCKS5, while the connection is established via HTTP or HTTPS agent. Axios does not support proxies directly, so the key element of configuration is selecting the correct agent.

Solution:

Connect the appropriate agent (http-proxy-agent, https-proxy-agent, socks-proxy-agent) depending on the protocol type being used.

const HttpsProxyAgent = require('https-proxy-agent');
const agent = new HttpsProxyAgent('http://user:pass@ip:port');

For SOCKS5:

const { SocksProxyAgent } = require('socks-proxy-agent');
const agent = new SocksProxyAgent('socks5://user:pass@ip:port');

407 Proxy Authentication Required – ошибка авторизации

Cause: Invalid username or password, missing Proxy-Authorization header, or incorrect connection string format.

Solution:

Check the syntax of the connection string: http://user:pass@ip:port. Make sure the agent correctly passes the authentication parameters.

const HttpsProxyAgent = require('https-proxy-agent');

const proxyUrl = 'http://username:password@82.211.9.160:50100';
const agent = new HttpsProxyAgent(proxyUrl);

Conclusion

Configuring Axios proxy is an essential step for working with anonymity, load balancing, and bypassing restrictions. The reliability of requests is ensured through proper proxy agent configuration, selection of compatible protocols, and well-thought-out error handling. At the same time, the quality of the proxy server directly affects the efficiency of the tool. Free proxies are generally unstable, often get blocked, and quickly become the cause of failures.

For production use, it is recommended to rely on paid solutions from trusted providers offering large IP pools, rotation support, and high uptime.

FAQ

Can Axios proxy be configured globally via environment variables?

Yes, Axios can indeed be configured globally to use a proxy server with environment variables: HTTP_PROXY, HTTPS_PROXY, and NO_PROXY. These variables can be set through system properties. To do this, open System Properties → Environment Variables, create a new variable (e.g., HTTP_PROXY), and specify the proxy server address as its value.

Is authentication required for residential proxies?

Axios does not distinguish between different types of proxies: residential, mobile, or datacenter — the authentication setup is the same. The main requirement is the correct URL format or a properly defined proxy.auth block.

What are the alternatives to Axios when working with intermediaries?

The main alternatives to Axios proxy use in Node.js are node-fetch and Got. Both libraries support HTTP/HTTPS proxies through environment variables as well as explicit configuration in code. Where possible, Got provides more flexible options for timeouts, retries, and request customization, while node-fetch has syntax more familiar to frontend developers. The choice depends on your specific needs and convenience.

Comments:

0 comments