Skip to content

Axios is one of the most common HTTP clients in JavaScript projects, and sooner or later many API workers need to send their requests through a proxy. Maybe your server must reach a partner API from a fixed outbound address, maybe a QA team wants to check how a service answers from another region, or maybe your company network only allows outbound traffic through a gateway. Whatever the reason, the configuration is not complicated, but it has a few quirks that catch people out. This guide walks through the options in order, shows a plain example, and ends with the limits you should plan for. Use proxies only for lawful work, respect the terms of every API and website you call, and follow the rules that apply where you operate.

How a proxy fits into an Axios request

A proxy is an intermediary server. Instead of opening a connection straight to the API host, your code opens a connection to the proxy and asks it to forward the request. For plain HTTP targets the proxy receives the full request and passes it on. For HTTPS targets the client normally sends a CONNECT request, the proxy opens a raw tunnel to the destination, and the TLS handshake then happens end to end between your code and the API. The proxy sees the destination host and port but not the encrypted content. The MDN article on proxy servers and tunneling explains this flow well, and the HTTP Semantics specification, RFC 9110, defines the CONNECT method.

It helps to be clear about where Axios runs. In Node.js, Axios uses the built-in http and https modules, so you control the connection. In a browser, Axios sits on top of XMLHttpRequest or fetch, and the browser decides which proxy to use. Page code cannot change it. Everything in this guide therefore applies to server-side code, scripts, workers and command-line tools.

What you need before you start

Gather four things from your proxy provider or your network team before touching code.

  • The proxy host name or address and the port.
  • The protocol the proxy speaks toward your client, usually HTTP or HTTPS. SOCKS is a different protocol and needs a different agent.
  • The authentication method, normally a username and password, or an allow-list of your own server addresses.
  • The rules of the plan you are using, such as how many connections or how much traffic you may use. Check the plan page rather than assuming.

Keep the credentials out of your source tree. Put them in environment variables such as PROXY_HOST, PROXY_PORT, PROXY_USER and PROXY_PASS, or in the secrets store your platform provides. If a secret ever lands in a repository, rotate it.

Option 1: the built-in proxy setting

Axios accepts a proxy object in the request config. It is the quickest way to try a proxy.

const axios = require("axios");

const response = await axios.get("https://api.example.com/v1/status", {
  proxy: {
    protocol: "http",
    host: process.env.PROXY_HOST,
    port: Number(process.env.PROXY_PORT),
    auth: {
      username: process.env.PROXY_USER,
      password: process.env.PROXY_PASS,
    },
  },
  timeout: 15000,
});

console.log(response.status);

This works well for simple requests and for plain HTTP targets. Be aware that behaviour for HTTPS targets has varied between Axios versions, and some versions send the request to the proxy in a way that does not create a proper tunnel. If you see strange certificate errors, empty responses or a proxy returning an error page for an HTTPS call, move on to the agent approach below. Always read the changelog of the exact Axios version you have installed.

Setting proxy: false turns off proxy handling for that request, including any proxy picked up from environment variables. That is useful when one call must go direct, or when you hand the job over to an agent.

Option 2: environment variables

Axios in Node.js can read the common proxy variables, HTTP_PROXY, HTTPS_PROXY and NO_PROXY, and many other tools read them too. This lets you change the proxy without editing code, which is handy for containers and CI jobs.

export HTTPS_PROXY="http://USER:PASS@proxy.example.net:8080"
export NO_PROXY="localhost,127.0.0.1,.internal.example"
node worker.js

Two cautions apply. First, variable names are case-sensitive on some systems and libraries check both upper and lower case, so set them consistently. Second, NO_PROXY is your friend: list internal hosts, health checks and metadata endpoints there so that they never travel through an external proxy by accident. Special characters in a password must be URL-encoded when you embed them in the URL form.

Option 3: a proxy agent

For HTTPS work, the approach many teams settle on is a dedicated agent such as the https-proxy-agent package, passed to Axios as httpsAgent while proxy is set to false. The agent performs the CONNECT tunnel properly and lets you tune connection reuse.

const axios = require("axios");
const { HttpsProxyAgent } = require("https-proxy-agent");

const agent = new HttpsProxyAgent(
  `http://${process.env.PROXY_USER}:${process.env.PROXY_PASS}@${process.env.PROXY_HOST}:${process.env.PROXY_PORT}`,
  { keepAlive: true }
);

const client = axios.create({
  baseURL: "https://api.example.com",
  httpsAgent: agent,
  proxy: false,
  timeout: 15000,
});

const { data } = await client.get("/v1/orders", { params: { page: 1 } });

Adding a package is a normal decision for a project, but treat it like any dependency: pin the version, read its release notes and let your usual review process approve it. Creating one shared client with axios.create is better than building a new agent for every request, because the agent keeps sockets open and reuses them.

If your provider hands you a SOCKS endpoint rather than an HTTP one, use a SOCKS agent in the same pattern. The protocol itself is described in RFC 1928, but you rarely need to read it to use a library.

A plain worked example

Imagine a small service that checks the order status of a partner's API every few minutes. The partner only accepts calls from a known outbound address, so your team routes the service through a proxy that offers a stable address.

  1. Store the four proxy values in environment variables on the host.
  2. Create one Axios client at start-up with a proxy agent, proxy: false, a baseURL, a timeout and a clear User-Agent that identifies your service.
  3. Add a request interceptor that attaches an identifier to each call so you can follow it through logs.
  4. Wrap calls so that a failure logs the HTTP status or the network error code, never the proxy password.
  5. Run a single call against a harmless endpoint and confirm the response before enabling the schedule.

The same client can then serve every part of the worker, and when the proxy details change you only edit the environment.

Testing that the proxy is really used

Do not assume. Verify in three ways.

  • Call an endpoint that echoes the caller's address and compare it with the address the same call shows when proxy: false and no agent are used.
  • Check the proxy dashboard or logs, if your provider offers them, to see that a request arrived.
  • Temporarily point the client at a wrong port and confirm that it fails. A client that still succeeds is clearly not going through the proxy you think it is.

It is also worth running the same request from a terminal with cURL to separate problems in your code from problems in the proxy or network. The guide on sending an HTTP request through a proxy with cURL gives you that baseline, and the walk-through for setting up a proxy in Node.js fetch is a useful comparison if part of your code base does not use Axios.

Timeouts, errors and retries

A proxied request has more places to fail than a direct one: the connection to the proxy, the proxy authentication, the tunnel to the target, the TLS handshake and the response. Axios timeout covers the time to receive a response, but it does not always capture every stage in the same way, so set explicit limits at the agent level too if your library allows it.

Common error signs include:

Symptom Likely area to check
ECONNREFUSED to the proxy Wrong host or port, or the proxy is not reachable from your network
HTTP 407 Missing or wrong proxy credentials
ETIMEDOUT or ECONNRESET Slow tunnel, idle sockets closed by a middlebox, or an overloaded target
Certificate errors A wrong tunnel mode for HTTPS, or a corporate proxy that inspects traffic
HTTP 429 from the API You are sending requests faster than the API allows

Never disable certificate verification to make an error disappear. That removes the protection TLS gives you. Retries deserve their own design, with limits, delays and care about which requests are safe to repeat. Read how to handle retry and timeout with a proxy before adding an automatic loop.

A final check before you ship: run the verification script in the environment where the code will actually run, not only on your laptop. Containers, CI runners and servers often differ in environment variables, outbound firewall rules and Node.js versions, and any of these can silently change which route a request takes. Log the resolved proxy host, never the credentials, at startup so that a wrong configuration is visible in the first minute rather than after a day of odd results.

It also helps to keep the proxy configuration in one module. Create a single function that builds the Axios instance, reads the proxy settings from the environment, and is imported everywhere else. When the provider, port or authentication method changes, you edit one place instead of searching the code base. Add a unit test that fails if the proxy variable is missing in production, so a misconfigured deployment stops early instead of quietly calling the API directly from the wrong address.

Limits and what to watch for

A proxy is a tool with boundaries, and API work makes them visible.

  • Rate limits and terms. A proxy does not change the rules of the API you call. Respect documented rate limits, authentication requirements and usage terms. If an API asks you to slow down, slow down.
  • Concurrency. Opening too many parallel connections through one proxy can hit plan limits or trigger errors. Cap concurrency in your client and read your plan details on the product page.
  • Added latency. An extra hop means extra time. Do not budget your timeouts as if the call were direct.
  • Secrets in logs. Axios error objects can contain the request config, which may include the proxy credentials. Log selected fields only.
  • Compliance. Know what data passes through the proxy and whether your own policies or local law restrict sending it through a third party.
  • Version drift. Proxy behaviour in HTTP libraries changes over time. Pin versions and keep a small integration test that proves the route works.

Summary

To use a proxy with Axios, remember that it works in Node.js and not in the browser. Use the built-in proxy option or environment variables for quick tests, and switch to a proxy agent with proxy: false for dependable HTTPS work. Keep credentials in environment variables, share one configured client, set sensible timeouts, and verify the route by comparing addresses and watching what happens when the proxy is wrong. Treat errors, retries and concurrency as part of the design, and always stay within the terms of the services you call. When you are ready to choose a proxy for your API work, the details are on the XPASS proxy page.

Frequently asked questions

Can Axios use a proxy in the browser?

No. In a browser the proxy is chosen by the browser or the operating system, and page code cannot set it. The proxy options in Axios apply to the Node.js build only.

Should I use the built-in proxy option or an agent?

For a quick test the built-in option or environment variables are enough. For HTTPS targets and production work, many teams prefer a dedicated proxy agent with proxy set to false, because it makes the tunnel behaviour explicit.

Where should I store proxy credentials?

In environment variables or a secrets manager, never in source code or in a repository. Load them at start-up and keep them out of log lines.

What timeout should I set on proxied requests?

There is no universal value. Start with a modest connect and response limit, measure your real traffic, and adjust. Proxied requests add a hop, so they usually need a little more headroom than direct ones.

About the author

Bob Kanokphon Thongdee, founder of XPASS VPN

Bob Kanokphon Thongdee

  • Founder of XPASS VPN
  • Co-founder of eSIMonline.asia
  • More than 7 years in online marketing
  • Founder of Cojourney Visa and Cojourney Travel

Need a proxy for this?

XPASS Proxy sells residential proxy traffic by the gigabyte, with the price shown before you pay.

See proxy plans

Keep reading

Proxy Guides

How to Set Up a Proxy in Node.js fetch

The built-in fetch in Node.js ignores proxy environment variables by default. This guide shows how to route it through a proxy with an undici dispatcher and test the result.

9 min read

Proxy Guides

How to Handle Retry and Timeout When Using a Proxy

Proxied requests have more places to fail. Learn how to set layered timeouts, choose which errors deserve a retry, add backoff and keep retries polite.

9 min read

Proxy Guides

How to Send an HTTP Request Through a Proxy with cURL

Use cURL to test an HTTP or SOCKS5 proxy from the command line: the right flags, authentication, environment variables, a verification routine and how to read errors.

9 min read