Main Website
Scraping
Updated on
February 24, 2025

Proxy in Axios: 3 Effective Setup Methods Explained

Axios is a popular JavaScript library used for making HTTP requests, offering an easy-to-use API and supporting features like request/response interception and promise-based handling. It simplifies making requests and handling responses, particularly when working with APIs. Axios is widely adopted in both browser and Node.js environments for its reliability and flexibility.

In the context of Axios, a proxy acts as an intermediary server that forwards requests from the client to the target API, often used to hide the client's real IP address or access content restricted by region. Using a proxy with Axios can enhance security, maintain anonymity, and manage network traffic effectively.

In this article, we’ll explore three effective methods for setting up proxies in Axios. Whether you’re working with a single static proxy, using a list of proxies, or leveraging the power of SOCKS5 proxies, we’ll guide you through each setup. We’ll also touch on advanced configurations, such as custom IP rotation and troubleshooting common issues, to help you optimize your proxy use.

Method 1: Static HTTP proxy

Method 2: HTTP Proxy list

Method 3: SOCKS5 proxy

Prerequisites

Before setting up proxies in Axios, follow these steps to prepare your project environment:

  • Create a New Node.js Project: Set up a new project folder where the code will reside. Run the following commands in the command prompt to create the folder and initialize a Node.js project:
mkdir axios-proxy-setup
cd axios-proxy-setup
npm init -y

This will create a package.json file with default values in the project directory.

  • Install Required Dependencies: Install the axios library and any additional dependencies required for proxy configuration:
npm install axios
  • Create a Project File: Set up the main project file where the axios configurations and requests will be implemented:
echo. > app.js
  • Update the package.json File: Edit the package.json file to include a start script for running the application. Open the file with a text editor or IDE, and replace the "scripts" section with:
"scripts": {
  "start": "node app.js"
}
  •  Verify the Setup: Test the setup by running the following command:
npm start

If everything is configured correctly, the application will run without errors, even though no code is implemented in app.js yet.

Method 1: Static HTTP proxy

A static HTTP proxy is the simplest form of proxy setup in Axios, where a single proxy server is used to route all your requests. This method is commonly used when you don’t need to switch between different proxies or manage multiple requests with different proxy settings. It’s ideal for straightforward applications where a single proxy is sufficient.

How to configure a static HTTP proxy in axios

To implement a static proxy in Axios, you have to define the proxy's host, port, protocol, and authentication credentials. Here's how to set it up:

const axios = require('axios');

// Make an HTTP request using a static proxy
axios.get('https://api.ipify.org/?format=json', {
    proxy: {
        host: 'proxyHost',        // Replace with your proxy host
        port: 8080,                  // Replace with your proxy port
        protocol: 'http',            // Proxy protocol: 'http' or 'https'
        auth: {
            username: 'proxyUser',   // Proxy username
            password: 'proxyPass'    // Proxy password
        }
    }
})
.then(res => {
    console.log('Proxy IP:', res.data);
})
.catch(err => {
    console.error('Error:', err.message);
});

Proxy Details:

  • host: IP or domain name of the proxy server (e.g., 123.45.67.89).
  • port: Port through which the proxy communicates (e.g., 8080).
  • protocol: Protocol used for the proxy (http or https).

Authentication: username and password are optional but required for private proxies. These credentials authenticate the connection to the proxy server.

For Webshare proxies, sign up for their free plan to access 10 free datacenter proxies. These proxies are shared, limited to 1GB of bandwidth per month, and include options for both rotating and static configurations. You’ll find the necessary proxy details (username, password, host, and port) in your Webshare account dashboard.

  • Endpoint Verification: The URL https://api.ipify.org/?format=json is a simple API that returns your IP address. When used with a proxy, it helps verify if the proxy configuration works correctly.

How to test the static proxy configuration

Save the code in a file (e.g., app.js) and execute it with:

npm start

If configured correctly, the output displays the IP address of the proxy server.

Method 2: HTTP Proxy list

Using an HTTP proxy list allows you to rotate multiple proxies for tasks like web scraping, load balancing, or avoiding rate limits. 

How to configure axios with a proxy list

Instead of using a single static proxy, you can configure Axios to randomly or sequentially select a proxy from a predefined list. Here's how you can set it up:

  • Prepare a Proxy List: A proxy list contains multiple proxy server details, including the host, port, protocol, and authentication credentials. 
  • Randomize or Rotate Proxies: Use JavaScript logic to randomly pick a proxy or iterate through the list.

Here’s an example of how to configure axios to work with a proxy list:

const axios = require('axios');

// Proxy list
const proxyList = [
    { host: 'proxyHost', port: 8080, protocol: 'http', auth: { username: 'user1', password: 'pass1' } },
    { host: 'proxyHost', port: 8081, protocol: 'http', auth: { username: 'user2', password: 'pass2' } },
    { host: 'proxyHost', port: 9090, protocol: 'http', auth: { username: 'user3', password: 'pass3' } }
];

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

// Make multiple HTTP requests with a random proxy
for (let i = 0; i < 5; i++) {
const proxy = getRandomProxy();

axios.get('https://api.ipify.org/?format=json', {
    proxy: {
        host: proxy.host,
        port: proxy.port,
        protocol: proxy.protocol,
        auth: proxy.auth
    }
})
.then(res => {
    console.log('Proxy IP:', res.data);
})
.catch(err => {
    console.error('Error:', err.message);
});
}

The getRandomProxy() function ensures that a random proxy is selected from the list for each request, useful for tasks requiring IP rotation.

How to test the HTTP proxy list configuration

Save the code in a file and execute it. The output should display IP addresses from the proxy list:

Method 3: SOCKS5 proxy

A SOCKS5 proxy offers more flexibility and security than HTTP proxies, as it supports various protocols and operates at the transport layer. Here’s how to configure and test a SOCKS5 proxy using axios.

How to configure a SOCKS5 proxy

Install Necessary Packages: Use the axios-socks5-agent package to enable SOCKS5 proxy support with axios. Install it via npm:

npm install axios socks-proxy-agent
  • Obtain SOCKS5 Proxy Credentials:
    • Proxy Host: The server address of the SOCKS5 proxy.
    • Proxy Port: The port on which the SOCKS5 proxy is running.
    • Authentication: Optional username and password for proxy authentication.

Here’s an example of configuring axios to use a SOCKS5 proxy:

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

// Define the SOCKS5 proxy configuration
const proxy = {
    host: 'proxyHost', // Replace with your proxy host
    port: 1080,        // Replace with your proxy port
    username: 'proxyUser', // Replace with your proxy username
    password: 'proxyPass'  // Replace with your proxy password
};

// Create a SOCKS5 proxy agent
const agent = new SocksProxyAgent(`socks5://${proxy.username}:${proxy.password}@${proxy.host}:${proxy.port}`);

// Make a request using the SOCKS5 proxy
axios.get('https://api.ipify.org/?format=json', { httpsAgent: agent })
    .then(response => {
        console.log('Proxy IP:', response.data);
    })
    .catch(error => {
        console.error('Error:', error.message);
    });

This script configures the proxy details (host, port, username, and password), creates a SocksProxyAgent to route traffic through the proxy, and uses axios to send a request to https://api.ipify.org.

How to test the SOCKS5 proxy configuration

Save the code in a file and run it. A successful request will display the proxy’s IP address.

Bonus method: Residential proxies in axios

Residential proxies use IP addresses assigned by internet service providers (ISPs) to ensure high anonymity and make requests appear as though they originate from real users. They’re ideal for web scraping, ad verification, and accessing geo-restricted content.

How to configure residential proxies

Here’s an example configuration for using residential proxies in Axios:

const axios = require('axios');

// Residential proxy settings
const proxy = {
    host: 'residential.proxy.provider.com', // Replace with your proxy host
    port: 8000,                             // Replace with your proxy port
    protocol: 'http',                       // Protocol ('http' or 'https')
    auth: {
        username: 'user123',                // Replace with your username
        password: 'password456'             // Replace with your password
    }
};

// Axios request using the residential proxy
axios.get('https://api.ipify.org/?format=json', {
    proxy: {
        host: proxy.host,
        port: proxy.port,
        protocol: proxy.protocol,
        auth: {
            username: proxy.auth.username,
            password: proxy.auth.password
        }
    }
})
.then(response => {
    console.log('Residential Proxy IP:', response.data);
})
.catch(error => {
    console.error('Error:', error.message);
});

This code defines the proxy settings and an axios GET request is then sent to https://api.ipify.org to fetch the public IP address, routing the request through the specified residential proxy. The proxy's IP address is printed if the request succeeds, while errors are logged to the console.

Run the code and confirm the proxified IP in the console matches the expected residential IP.

Advanced proxy configuration

When working with proxies in axios, advanced configurations can help customize how requests are routed, optimize performance, and increase anonymity. Below are specific tweaks like tinkering the proxy config and custom IP rotation per request and why you might need them.

Tinkering the proxy config

Tinkering the proxy configuration means adjusting and customizing proxy-related settings in your application to suit specific needs. This could involve altering request timeouts, retry logic, error-handling mechanisms, and choosing the appropriate proxy protocols like HTTP, HTTPS, or SOCKS5. Here’s why it’s important:

  • Optimize Performance: Adjusting timeouts ensures that your application doesn’t hang while waiting indefinitely for a response. You can configure faster retries or switch to alternative proxies when needed to improve the overall request throughput.
  • Improve Reliability: By setting up fallback proxies or retry mechanisms, you can ensure the application continues to function even when the primary proxy fails.
  • Protocol Flexibility: Different use cases might demand different proxy protocols. For instance:
  • HTTP/HTTPS Proxies: Suitable for most general web scraping or API calls.
  • SOCKS5 Proxies: More secure and versatile, especially when dealing with UDP connections or non-standard protocols.
  • Error Handling: Configuring how errors are managed ensures that unexpected failures don’t break the system. For example, retries can be added for certain HTTP status codes (e.g., 429 Too Many Requests).

With axios, you can configure these settings in your request options.

axios.get('https://api.ipify.org', {
    timeout: 5000, // Set timeout to 5 seconds
    proxy: {
        protocol: 'socks5', // Use SOCKS5 proxy for enhanced security
        host: 'proxy.example.com',
        port: 1080,
        auth: {
            username: 'user',
            password: 'pass'
        }
    }
})
.catch(err => console.error('Request failed:', err));

Custom IP rotation per request

Custom IP rotation involves changing the proxy IP address used for each outgoing request. This can be implemented manually by switching proxies programmatically or automatically by using a proxy provider with built-in rotation functionality. Here’s why it’s important:

  • Avoid Detection: Many websites detect repeated requests from the same IP address and block them. Rotating IPs makes each request appear to originate from a different user.
  • Bypass Rate Limits: Websites often impose limits on how many requests can come from a single IP in a specific time period. Rotating IPs ensures uninterrupted access.
  • Access Geo-Restricted Content: Rotating IPs from different regions allows you to fetch data localized to those areas or bypass regional restrictions. For example, accessing prices in a specific country’s currency.
  • Enhance Privacy: Rotating IPs prevents tracking and ensures anonymity, making it harder for third parties to trace your activities.

In axios, you can rotate proxies by maintaining an array of proxy configurations and selecting a random one for each request as we discussed in one of the methods above.

Troubleshooting common issues

When configuring proxies in Axios, developers often encounter issues related to connectivity, authentication, or user agent headers. Here's an overview of common problems and how to resolve them.

Incorrect proxy configuration

Issue: The proxy host, port, or authentication details are incorrect, resulting in connection errors.

Error: connect ECONNREFUSED 

Fix:

  • Double-check the proxy details provided by your provider (host, port, username, and password).
  • Ensure the protocol (http, https, or socks5) matches the proxy type.
  • Test the proxy using a tool like curl to confirm connectivity.
curl -x http://username:password@proxy-host:port https://api.ipify.org

Missing or misconfigured user-agent header

Issue: Some websites block requests that lack a proper User-Agent header, interpreting them as bot traffic. Error example is as:

Error: Request blocked by server.

Fix: Set the User-Agent header in your axios requests to mimic a regular browser as shown in the below example:

const axios = require('axios');

axios.get('https://api.ipify.org', {
    headers: {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    },
    proxy: {
        host: 'proxy-host',
        port: 6540,
        auth: {
            username: 'proxy-username',
            password: 'proxy-password'
        }
    }
})
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));

Proxy authentication fails

Issue: The server rejects requests because the authentication credentials are missing or incorrect. Error example is as:

Error: 407 Proxy Authentication Required

Fix:

  • Verify that the auth object in your proxy configuration contains the correct username and password.
  • Ensure the proxy server supports the authentication method being used.

Wrapping up: proxy in axiosProxies bring flexibility and control to your axios requests, allowing you to handle tasks like bypassing restrictions, rotating IPs, or enhancing privacy. By understanding different proxy types and configurations, you can tailor your setup for specific requirements. With the right configuration and troubleshooting approach, you can leverage proxies effectively in your applications.

Proxy in Puppeteer: 3 Effective Setup Methods Explained

Proxy in Node.js: 5 Common Setup Methods Explained

Proxy in cURL: 3 Effective Setup Methods Explained