How to Set Per-Request Proxy in Axios
This article explains how to configure and override proxy settings on
individual HTTP requests using the Axios library in Node.js. While Axios
supports default, instance-level, and environment-based proxies, you can
customize or bypass proxy behavior for specific endpoints using the
proxy configuration option or custom HTTP/HTTPS agents.
Using the
proxy Configuration Option
Axios provides a built-in proxy configuration property
that can be passed directly to request methods such as
axios.get(), axios.post(), or
axios.request(). Passing this object overrides any
instance-level proxy settings for that single execution.
The proxy configuration object accepts the following
fields:
protocol: The protocol used to connect to the proxy (e.g.,'http'or'https').host: The hostname or IP address of the proxy server.port: The port number of the proxy server.auth: An optional object containingusernameandpasswordcredentials for basic authentication.
Example: Per-Request Proxy Override
const axios = require('axios');
async function fetchDataWithProxy() {
try {
const response = await axios.get('https://api.example.com/data', {
proxy: {
protocol: 'http',
host: '127.0.0.1',
port: 8080,
auth: {
username: 'proxy_user',
password: 'proxy_password'
}
}
});
console.log(response.data);
} catch (error) {
console.error('Request failed:', error.message);
}
}
fetchDataWithProxy();Disabling Proxies on a Single Request
If an Axios instance contains a default proxy, or if environment
variables (such as HTTP_PROXY or HTTPS_PROXY)
are automatically routing traffic through a proxy, you can bypass the
proxy for a specific request by setting proxy: false.
const response = await axios.get('https://api.example.com/direct', {
proxy: false
});Using Custom Agents for Advanced Proxying
For scenarios requiring SOCKS proxies, HTTPS tunneling, or custom
connection handling, Axios's default proxy config may be
insufficient. In these cases, you can attach custom agent instances
(like https-proxy-agent or socks-proxy-agent)
to the httpAgent or httpsAgent request
options.
When using custom agents, set proxy: false to ensure
Axios does not attempt to apply its native proxy handling alongside the
agent.
const axios = require('axios');
const { HttpsProxyAgent } = require('https-proxy-agent');
const customAgent = new HttpsProxyAgent('http://proxy.example.com:8080');
async function fetchWithCustomAgent() {
const response = await axios.get('https://api.example.com/secure-data', {
httpsAgent: customAgent,
proxy: false
});
console.log(response.data);
}
fetchWithCustomAgent();