How to Configure an HTTP Proxy in Axios for Node.js

Configuring an HTTP proxy in Axios allows Node.js applications to route outbound web requests through an intermediary server for security, load balancing, or bypassing network restrictions. This article explains how to configure proxies in Axios using its built-in proxy configuration object, how to set default proxy settings across instances, and how to use dedicated proxy agents for handling secure HTTPS tunneling.

Method 1: Using the Built-in proxy Config

Axios provides a native proxy configuration object that works out of the box for basic HTTP proxy routing. You can pass the proxy parameters directly inside the request config.

const axios = require('axios');

axios.get('http://api.example.com/data', {
  proxy: {
    protocol: 'http',
    host: '127.0.0.1',
    port: 8080,
    auth: {
      username: 'proxyUser',
      password: 'proxyPassword'
    }
  }
})
.then(response => {
  console.log(response.data);
})
.catch(error => {
  console.error('Request failed:', error.message);
});

The auth field is optional and only required if the proxy server enforces authentication.


Method 2: Global Configuration via Axios Instances

If all requests should go through the same proxy, define the configuration once by creating an Axios instance.

const axios = require('axios');

const apiClient = axios.create({
  baseURL: 'http://api.example.com',
  proxy: {
    protocol: 'http',
    host: 'proxy.corporate.net',
    port: 3128
  }
});

// All requests using apiClient will automatically route through the proxy
apiClient.get('/users')
  .then(res => console.log(res.data))
  .catch(err => console.error(err));

To disable a proxy for a specific request when an instance is used, pass proxy: false in that request's options.


Method 3: Using https-proxy-agent for HTTPS Tunneling

Axios's built-in proxy option has known limitations when tunneling HTTPS traffic over an HTTP proxy. For robust HTTPS proxy support, use the https-proxy-agent package.

  1. Install the package:
npm install https-proxy-agent
  1. Configure Axios using the httpsAgent option:
const axios = require('axios');
const { HttpsProxyAgent } = require('https-proxy-agent');

const proxyUrl = 'http://username:password@proxy.example.com:8080';
const httpsAgent = new HttpsProxyAgent(proxyUrl);

axios.get('https://api.example.com/secure-data', { httpsAgent })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('HTTPS Proxy Error:', error.message);
  });

Method 4: Environment Variables

Axios natively respects standard environment variables in Node.js environments. If no custom proxy or agent is configured, Axios automatically routes traffic through the proxies defined in your environment:

To disable automatic environment variable proxy resolution, set proxy: false in the Axios configuration.