How To Set a Proxy in Axios: Definitive Guide

Learn how to set up proxies in Axios and read about Bright Data proxies that are compatible with Axios.
9 min read
How To Set a Proxy in Axios

This Axios proxy guide will cover the following topics:

  • Why you should use proxies in Axios.
  • How to set an HTTP, HTTPS, or SOCKS proxy with Axios.
  • How to deal with authentication and proxy rotation.

What Is Axios and Why You Need a Proxy?

Axios is one the most widely-used HTTP clients in the JavaScript ecosystem. It offers a Promise-based, easy-to-use, intuitive API for performing HTTP requests and dealing with custom headers, configurations, and cookies.

Why do you need a proxy in Axios? Simple! By routing your requests through a proxy, you can mask your IP address, making it more challenging for the target server to identify and block you. This added layer of privacy helps maintain the integrity of your application and avoids IP bans or restrictions. You can achieve the same result with Fetch as explained in our node-fetch proxy guide.

Using a Proxy in Axios

In this axios proxy section, you will see how to set an HTTP, HTTPS, or SOCKS proxy in Axios.

Prerequisites

First, you need to make sure the axios npm package is installed. Add it to your project’s dependencies with:

npm install axios 

In Node.js, Axios natively supports HTTP and HTTPS proxies via the proxy config. So, if you want to use HTTP/HTTPS proxies with Axios in a Node.js application, you are ready to go!

If you instead want to use a non-HTTP/S proxy, you need to rely on the Proxy Agents project. This provides http.Agent implementations to integrate Axios with proxies in different protocols. In detail, the different npm libraries exposed by the project categorized by the protocol are:

Amazing! You are ready to set proxies in Axios!

HTTP/HTTPS Proxies

This is what the URL of your HTTP/HTTPS proxy should look like:

"<PROXY_PROTOCOL>://<PROXY_HOST>:<PROXY_PORT>" 

<PROXY_PROTOCOL> will be “http” for HTTP proxies and “https” for HTTPS proxies. <PROXY_HOST> is generally a raw IP, while <PROXY_PORT> is the port the proxy server listens to.

For example, suppose this is the URL of your HTTP proxy:

"http://47.88.62.42:80"

You can set this proxy in Axios as follows:

axios.get(targetURL, {

    proxy: { 

        protocol: "http", 

        host: "48.88.62.42",

        port: "80"

    }

})

As you can see, it all boils down to splitting the proxy URL into two parts and specifying them correctly in the proxy configuration. Axios will now make the request to the URL passed as a parameter through the specified HTTP proxy server.

Let’s verify that the above Axios proxy approach works! 

Retrieve the URL of an HTTP or HTTPS proxy server for free online. For example, take a look at this one:

Protocol: HTTP; IP Address: 52.117.157.155; Port: 8002

The complete proxy URL will be “http://52.117.157.155:8002.”

To verify that the proxy works as expected, you can target the /ip endpoint from the HTTPBin project. This public API returns the IP of the incoming request, so it should return the IP of the proxy server. 

The snippet of the Node.js script will be:

import axios from "axios"

async function testProxy() {

    // perform the desired request through the HTTP proxy

    const response = axios.get("https://httpbin.io/ip", {

        proxy: { 

            protocol: "http", 

            host: "52.117.157.155",

            port: "8002" 

        }

    })

    // print the result

    console.log(response.data)

}

testProxy()

Execute the script and it should log:

{ "origin": "52.117.157.155" }

This is the same IP as the proxy server, which means that the proxy server works as expected and your IP is safe! 

Unfortunately, you will not get the same result if you run the script. In detail, it will end with an error. Why? Because free proxies are short-lived and unreliable! You can use them for learning purposes but cannot rely on them in a real-world scenario. 

Warning: Free proxy services are unreliable, slow, error-prone, data-greedy, and short-lived. Avoid them! 

The solution? Premium proxies from Bright Data, the best provider in the market. Subscribe and try our reliable proxies for free.

SOCKS Proxies

If you try to set the “socks” string in the protocol field of the proxy config object, you will get the following error:

AssertionError [ERR_ASSERTION]: protocol mismatch

  // ...

 {

  generatedMessage: false,

  code: 'ERR_ASSERTION',

  actual: 'dada:',

  expected: 'http:',

  operator: '=='

}

That occurs because Axios does not natively support SOCKS proxies. Thus, you need an extra dependency to achieve the desired result.

Add the socks-proxy-agent npm library to your project’s dependencies with the command below:

npm install socks-proxy-agent

This package allows you to connect to a SOCKS proxy server while making HTTP or HTTPS requests in Axios.

Then, import the SOCKS proxy agent implementation from the library:

const SocksProxyAgent = require("socks-proxy-agent")

Or if you are an ESM user:

import { SocksProxyAgent } from "socks-proxy-agent"

Suppose this is the URL of your SOCKS proxy:

"socks://183.88.74.73:4153"

Note that the proxy protocol can be one of the values: “socks,” “socks5,” “socks4.”

Store it in a variable and pass it to the SocksProxyAgent constructor:

const proxyURL = "socks://183.88.74.73:4153"

const proxyAgent = new SocksProxyAgent(proxyURL)

SocksProxyAgent() initializes an http.Agent instance to perform HTTP/HTTPS requests through the proxy URL.

You can now use a SOCKS proxy with Axios as follows:

axios.get(targetURL, { 

    httpAgent: proxyAgent,     

    httpsAgent: proxyAgent 

})

httpAgent and httpsAgent define the custom agent to use when performing HTTP and HTTPS requests, respectively. In other words, the HTTP or HTTPS request made by Axios will go through the specified SOCKS proxy. In a similar way, you can use the https-proxy-agent npm package as an alternative way to set HTTP/HTTPS proxies in Axios.

Put it all together:

import axios from "axios"

import { SocksProxyAgent } from "socks-proxy-agent"

async function testProxy() {

    // replace with the URL of your SOCKS proxy 

    const proxyURL = "socks://183.88.74.73:4153"

    // define the HTTP/HTTPS proxy agent

    const proxyAgent = new SocksProxyAgent(proxyURL)

    // perform the request via the SOCKS proxy

    const response = await axios.get("https://httpbin.io/ip", { 

        httpAgent: proxyAgent,     

        httpsAgent: proxyAgent 

    })

    // print the result

    console.log(response.data) // { "origin": "183.88.74.73" }

}

testProxy()

Follow the link for other examples of how to configure a SOCKS proxy in Axios.

Axios Proxy: Advanced Use Cases

Now that you know the basics of Axios proxy integration, you are ready to delve into more complex techniques.

Setting a Proxy Globally

You can set a proxy globally by specifying it directly in an Axios instance:

const axiosInstance = axios.create({

    proxy: { 

        protocol: "<PROXY_PROTOCOL>", 

        host: "<PROXY_HOST>",

        port: "<PROXY_PORT>" 

    },

    // other configs...

})

Or if you are a Proxy Agents user:

// proxy Agent definition ...

const axiosInstance = axios.create({

    httpAgent: proxyAgent,     

    httpsAgent: proxyAgent 

})

All requests made with axiosInstance will now automatically go through the specified proxy.

Dealing With Proxy Authentication in Axios

To allow only paying users access to premium proxies, proxy providers protect them with authentication. Trying to connect to an authenticated proxy without a username and password will result in a 407 Proxy Authentication Required error.

 In particular, here is the syntax of the URL of an authenticated proxy:

[<PROTOCOL>://]<USERNAME>:<PASSWORD>@<HOST>[:<PORT>]

For example, a real-world URL to connect to an authenticated proxy might be:

http://admin:[email protected]:8391

In this case, the proxy URL field would be: 

  • <PROTOCOL>: HTTP
  • <HOST>: 156.127.0.192
  • <PORT>: 8391
  • <USERNAME>: admin 
  • <PASSWORD>: lK4w90MEe45YIkOpk

To deal with proxy authentication in Axios you only have to specify the username and password in the auth field of proxy:

axios.get(targetURL, {

    proxy: { 

        protocol: "http", 

        host: "156.127.0.192",

        port: "8381",

        auth: {

            username: "admin",

            password: "lK4w90MEe45YIkOpk"

        }

    }

})

Great! That is as simple as that!

If you are instead a Proxy Agents user, you have two ways to deal with authentication:

  1. Add the credentials directly in the proxy URL:
var proxyAgent = new SocksProxyAgent("http://admin:[email protected]:8391")
  1. Set the username and password options in a URL object:
const proxyOpts = new URL("http://156.127.0.192:8391")

proxyOpts.username = "admin"

proxyOpts.password = "lK4w90MEe45YIkOpk"

const proxyAgent = new SocksProxyAgent(proxyOpts)

The same approaches also work with HttpsProxyAgent.

Setting Proxies via Environment Variables

Another way to configure a proxy globally in Axios is by setting the following environment variables:

  • HTTP_PROXY: The URL of the proxy server to use for HTTP requests.
  • HTTPS_PROXY: The URL of the proxy server to use for HTTPS requests.

For example, set them on Linux or macOS with the commands below:

export HTTP_PROXY = "[<PROTOCOL>://]<USERNAME>:<PASSWORD>@<HOST>[:<PORT>]"

export HTTPS_PROXY = "[<PROTOCOL>://]<USERNAME>:<PASSWORD>@<HOST>[:<PORT>]"

When Axios detects these environment variables, it reads from them the proxy settings, including the credentials for authentication. Set the proxy field to false to make Axios ignore those environment variables. Keep in mind that you can also define a NO_PROXY env as a comma-separated list of domains that should not be proxied.

Note that the same mechanism also works when using proxies in cURL.

Implementing Rotating Proxies

If you use the same proxy server a lot of times, the target site will eventually block its IP address. To prevent that, it is essential to ensure that each request you perform originates from a different proxy server. A straightforward method to achieve that is as follows:

  1. Define a list of objects, each containing the information to connect to a different proxy.
  2. Randomly select a proxy object before each request.
  3. Configure the selected proxy in Axios.

The above approach assumes that you have access to a pool of reliable proxy servers. Acquiring access to many servers can cost you a lot of money in fees. Plus, integrating that logic into your code can be cumbersome and boilerplate.

This is where Bright Data steps in, offering rotating proxies that automatically switch IP addresses for you! You will gain access to proxies that supply a fresh IP address each time you connect. These proxy servers are accessible in 195 countries, have exceptional network uptime, and guarantee a success rate of 99.9%. Give Bright Data’s rotating proxies a try!

Conclusion

In this Axios proxy tutorial, you learned why to adopt proxies in Axios and how to do it. You now know how to set up an HTTP/HTTPS/SOCKS proxy in Axios. As seen here, that takes only a few lines of code!

You also realized that you should not use free proxy services. So, it only remains to choose which proxy provider to adopt. Save time and energy and go for the best on the market, Bright Data.

Bright Data controls the best proxy servers in the world, serving Fortune 500 companies and over 20,000 customers. Its worldwide proxy network involves:

Overall, this is one of the largest and most reliable proxy networks available.

No credit card required

No credit card required