To configure an Axios proxy in Node.js, pass a proxy object with an explicit protocol, host, port, and optional authentication fields, add a bounded timeout, and verify the observed route through an endpoint you own or are authorized to test. Use environment variables when one process intentionally shares a route, and set proxy: false when a custom HTTP or SOCKS agent must control the connection without Axios also applying proxy environment settings.
Scope: this guide covers native proxy configuration, proxy authentication, environment variables, custom agents, timeouts and errors, and safe logging for Axios in Node.js. Use the multi-client overview for a broader comparison or the Developer Guides hub for adjacent integrations.
An Axios proxy request crosses several independent boundaries: the application config, local DNS and network, the proxy connection, proxy authentication, an optional CONNECT tunnel, TLS to the destination, and the destination response. Treating all of them as one generic “proxy error” makes repairs slower and can expose secrets. The examples below use reserved .invalid hostnames and environment variables; replace them only inside an approved test environment.
Use an explicit Axios proxy config first
The smallest useful Axios proxy config makes the route visible in code review without embedding credentials in a URL. Axios documents the proxy request option in its official request configuration. Write the proxy protocol explicitly, parse the port as a number, keep the destination URL separate, and set a total request timeout.
import axios from 'axios';
const client = axios.create({
proxy: {
protocol: 'http',
host: 'HOST',
port: Number(process.env.PROXY_PORT || 3128),
},
timeout: 15000,
});
const response = await client.get(
'https://DESTINATION.example/proxy-check',
{ validateStatus: status => status >= 200 && status < 500 },
);
console.log({ status: response.status });
This Axios proxy example deliberately records only the response status. A diagnostic endpoint can return the source address it observes, but logs should not include proxy credentials, complete response bodies, cookies, authorization headers, personal data, or uncontrolled query strings. Compare one direct baseline with one proxied request before increasing traffic.
Keep proxy authentication in separate fields
When the proxy uses HTTP Basic authentication, place the username and password inside the proxy auth object. Do not concatenate them into a checked-in URL. Load them from an approved secret mechanism, verify that both values exist, and make sure errors or debug objects are sanitized before they leave the process.
import axios from 'axios';
const { PROXY_USERNAME, PROXY_PASSWORD } = process.env;
if (!PROXY_USERNAME || !PROXY_PASSWORD) {
throw new Error('Proxy credentials are not configured');
}
const response = await axios.get('https://DESTINATION.example/proxy-check', {
proxy: {
protocol: 'http',
host: 'HOST',
port: 3128,
auth: {
username: PROXY_USERNAME,
password: PROXY_PASSWORD,
},
},
timeout: 15000,
});
console.log({ status: response.status });
An HTTP 407 response belongs to the proxy-authentication boundary. A destination 401 or 403 belongs to the destination or application-account boundary. Rotating a proxy password will not repair a destination login failure. The proxy authentication guide compares username/password access with IP allowlisting and explains why a changing public source address can break an allowlist.
Use Axios proxy environment variables deliberately
Axios can use conventional HTTP_PROXY, HTTPS_PROXY, and NO_PROXY environment variables in Node.js. Axios proxy environment variables are useful when a bounded process, container, or scheduled job intentionally shares one route. They are less obvious than a request-level config because child processes and unrelated calls can inherit them.
import axios from 'axios';
process.env.HTTPS_PROXY = process.env.APPROVED_PROXY_URL ||
'http://HOST:3128';
process.env.NO_PROXY = 'localhost,.internal.example.invalid';
const response = await axios.get(
'https://DESTINATION.example/proxy-check',
{ timeout: 15000 },
);
console.log({ status: response.status });
Inject the real proxy URL through the deployment platform rather than assigning it in application source. Treat every NO_PROXY entry as a direct-routing exception: an exact host or justified suffix is easier to audit than a broad wildcard. Document whether uppercase and lowercase variants are set by the runtime, because libraries and operating systems can differ.
Environment policy also affects test repeatability. Record which variables were present without recording their secret values, and clear temporary values after an isolated diagnostic. If a cURL probe works but Axios fails, compare each program’s environment and bypass interpretation rather than assuming identical behavior.
Use proxy false when a custom agent owns routing
The setting proxy: false tells Axios not to apply its normal proxy object or proxy environment variables. This is important when a custom Axios proxy agent creates the socket or tunnel. Without the explicit opt-out, an inherited environment variable can compete with the agent and produce a route that is hard to explain.
import axios from 'axios';
import { HttpsProxyAgent } from 'https-proxy-agent';
const proxyUrl = process.env.APPROVED_PROXY_URL ||
'http://HOST:3128';
const agent = new HttpsProxyAgent(proxyUrl);
const response = await axios.get('https://DESTINATION.example/proxy-check', {
proxy: false,
httpAgent: agent,
httpsAgent: agent,
timeout: 15000,
});
console.log({ status: response.status });
Use a maintained agent package that matches the required proxy protocol. Review its supported Node versions and release history, pin dependencies through the project’s normal lockfile, and update after testing. The official proxy-agents monorepo documents the HTTP, HTTPS, SOCKS, and environment-aware agents in that package family.
Choose HTTP and SOCKS agents from the route design
The standard Axios proxy object is designed for HTTP or HTTPS proxy behavior. A SOCKS endpoint needs a SOCKS-aware agent. Set proxy: false, attach the agent to both Axios agent fields when the application can request both HTTP and HTTPS destinations, and verify whether destination DNS should be resolved locally or by the SOCKS route.
import axios from 'axios';
import { SocksProxyAgent } from 'socks-proxy-agent';
const socksUrl = process.env.APPROVED_SOCKS_URL ||
'socks5h://HOST:1080';
const agent = new SocksProxyAgent(socksUrl);
const response = await axios.get('https://DESTINATION.example/proxy-check', {
proxy: false,
httpAgent: agent,
httpsAgent: agent,
timeout: 15000,
});
console.log({ status: response.status });
The socks5h form indicates proxy-side hostname resolution in tools that support that convention. Local versus remote DNS is an architecture choice, not proof of anonymity. Test the installed package and actual endpoint because authentication and DNS features vary. A separate proxy verification guide explains why an observed egress address is only one layer of evidence.
Bound time with timeout and AbortController
A total Axios timeout prevents an abandoned request from waiting indefinitely, while an AbortController lets the surrounding task cancel work deliberately. Node documents the standard controller in its AbortController reference. Use one clear deadline and avoid stacking uncoordinated timers that can report the same failure twice.
import axios from 'axios';
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 12000);
try {
const response = await axios.get(
'https://DESTINATION.example/proxy-check',
{
proxy: {
protocol: 'http',
host: 'HOST',
port: 3128,
},
signal: controller.signal,
timeout: 10000,
},
);
console.log({ status: response.status });
} finally {
clearTimeout(timer);
}
Set retry policy above the request layer and retry only operations that are safe to repeat. Bound the attempt count, add backoff, honor destination rate-limit responses, and stop on authentication or policy errors. A proxy does not make a non-idempotent action safe.
Verify the route with controlled evidence
Begin with a direct request to an owned or approved diagnostic endpoint, then run one proxied request with the same method and headers. Record UTC time, application version, Axios version, expected proxy identifier, response status, observed egress when the endpoint provides it, and elapsed time. Redact all secrets and user data.
- Prove that the destination works directly when policy permits.
- Resolve and connect to the proxy host and port.
- Confirm credentials or source-IP allowlisting.
- Confirm the tunnel and TLS certificate path.
- Compare the observed egress with the expected assignment.
- Run one authorized destination action at conservative volume.
- Classify failures before changing config or adding retries.
The Mexela Proxy Checker can show the address its own server observes, while the checker interpretation guide explains what that result cannot prove. Use the real application’s destination only with authorization and within its rules.
Diagnose an Axios proxy not working by layer
Axios exposes a response, request, error code, and config context depending on the failure. Its official error-handling guide explains the primary error branches. Log only a small allowlist of fields; dumping the whole config can disclose headers and proxy authentication.
import axios from 'axios';
try {
await axios.get('https://DESTINATION.example/proxy-check', {
proxy: {
protocol: 'http',
host: 'HOST',
port: 3128,
},
timeout: 10000,
});
} catch (error) {
if (!axios.isAxiosError(error)) throw error;
console.error({
name: error.name,
code: error.code || null,
status: error.response?.status || null,
method: error.config?.method || null,
});
}
| Symptom | Likely boundary | Next controlled check |
|---|---|---|
ENOTFOUND |
DNS for proxy or destination | Identify which hostname failed and which side should resolve it. |
ECONNREFUSED |
Proxy listener or firewall | Confirm scheme, host, port, service status, and outbound rules. |
| HTTP 407 | Proxy authentication | Check the approved credential source or source-IP allowlist. |
| TLS certificate error | Proxy TLS, CONNECT tunnel, or destination trust | Inspect the certificate chain; do not disable validation. |
| HTTP 401 or 403 | Destination account or policy | Stop retries and confirm destination authorization. |
| HTTP 429 | Destination rate limit | Honor the limit, reduce volume, and prefer a documented API. |
ECONNABORTED or cancellation |
Time budget | Measure DNS, connect, tunnel, TLS, and response timing separately. |
If the same endpoint works in Python but not Node, compare environment variables, DNS, certificate stores, agent behavior, and dependency versions. The Python Requests proxy guide provides the corresponding client model. For a complete hop-by-hop sequence, follow the proxy troubleshooting guide.
Protect credentials, logs, and agent resources
Proxy URLs can contain usernames and passwords, and Axios error objects can include request config. Do not log complete URLs, config objects, request headers, response bodies, cookies, tokens, or agent options. Build a small sanitized diagnostic object as shown above. Restrict access to logs and set a retention period.
Keep secrets in the deployment platform, rotate them after suspected exposure, and avoid command-line arguments that can appear in process listings. Do not commit local environment files. Destroy long-lived custom agents during controlled shutdown when the package exposes a cleanup method; Node’s HTTP Agent documentation explains socket reuse, pooling, and why unused agents consume resources.
Separate Axios behavior from Node.js transport behavior
The upstream Axios request configuration defines native proxy fields and the proxy: false escape hatch when an agent owns routing. The Undici EnvHttpProxyAgent reference documents environment-proxy precedence for Undici-based clients, and the current Node.js fetch documentation defines the built-in Fetch boundary. Do not assume Axios, Fetch, and every agent share one proxy implementation.
Expected observation: one explicitly configured Axios request uses the intended proxy, proxy authentication is distinct from destination authentication, the selected environment or agent owns routing, and timeout/error logs preserve the failed boundary without serializing secrets.
Operational limits: an Axios success does not prove browser traffic, Fetch, or another Node.js library uses the same route. Keep retries bounded, destroy custom agents during shutdown, follow destination rules, and never log full configuration objects containing credentials.
Choose capacity only after the client passes
If a permitted Node.js service needs one consistent egress address and accountable ownership, compare the measured session and concurrency requirements with current private proxy options. Review the relevant Mexela option only after the acceptance test is repeatable.
Frequently asked questions
How do I set a proxy in Axios?
In Node.js, pass a proxy object with an explicit protocol, host, port, and optional auth fields to axios.get() or axios.create(). Add a bounded timeout and verify the route through an owned or approved endpoint.
Does Axios use HTTP_PROXY and HTTPS_PROXY?
Axios can use conventional proxy environment variables in Node.js, along with NO_PROXY bypass rules. Scope them to the smallest process and document inherited values because they can affect calls that do not contain an explicit proxy object.
What does proxy: false do in Axios?
proxy: false disables Axios proxy config and environment-variable proxy resolution for that request. Use it when a custom HTTP, HTTPS, or SOCKS agent is the single component responsible for routing.
Can Axios use a SOCKS5 proxy?
Yes, through a SOCKS-aware Node agent attached with httpAgent and httpsAgent. Set proxy: false, choose local or proxy-side DNS deliberately, and verify the installed agent package and endpoint capabilities.
Why does my Axios proxy return 407?
HTTP 407 normally means the proxy requires authentication or rejected the supplied proxy credentials. Check the proxy auth object, secret source, or source-IP allowlist; do not confuse it with a destination 401 or 403.
Why does an Axios proxy work in Node.js but not the browser?
Node Axios controls its own sockets and agents, while browser Axios uses browser and operating-system networking, proxy policy, CORS, extensions, and cookies. Browser code cannot normally select an arbitrary authenticated network proxy for one request.

