v1.10.82-f67ee7d
Skip to main content
← Back to Code Snippets

JavaScript Axios Proxy

Complete Axios proxy integration example for JavaScript/Node.js with Hex Proxies. Includes authentication, timeouts, and error handling.

JavaScriptAxios
Install:npm install axios https-proxy-agent
JavaScript / Axios
const axios = require("axios");
const { HttpsProxyAgent } = require("https-proxy-agent");

const agent = new HttpsProxyAgent(
  "http://user:pass@gate.hexproxies.com:8080"
);

async function fetchWithProxy() {
  try {
    const response = await axios.get("https://httpbin.org/ip", {
      httpsAgent: agent,
      timeout: 30000,
    });
    console.log("Origin IP:", response.data.origin);
  } catch (error) {
    if (error.code === "ECONNREFUSED") {
      console.error("Proxy connection refused");
    } else {
      console.error("Request failed:", error.message);
    }
  }
}

fetchWithProxy();

Why Axios for Proxy Work in Node.js

Axios has established itself as the most popular HTTP client in the JavaScript ecosystem, with over 45 million weekly npm downloads. Its promise-based API, automatic JSON transformation, and interceptor system make it an excellent foundation for proxy-driven workflows in Node.js. Unlike the built-in `http` module, Axios provides a high-level interface that handles response parsing, error categorization, and request/response transformation out of the box, letting developers focus on proxy routing logic rather than low-level HTTP mechanics.

The Node.js runtime is particularly well-suited for proxy workloads due to its non-blocking I/O model. A single Node.js process can manage thousands of concurrent proxied requests through gate.hexproxies.com:8080 without spawning threads. Combined with Axios's clean API, this makes Node.js a compelling choice for building proxy middleware services, data collection APIs, and real-time monitoring tools that need to route traffic through rotating IP addresses.

Configuration Patterns

Axios does not have native proxy support for HTTPS destinations, so you need the `https-proxy-agent` package to create an agent that tunnels HTTPS requests through the HTTP proxy. Instantiate the agent once with your proxy URL including credentials, then pass it as `httpsAgent` in your Axios config. For HTTP-only targets, use the `http-proxy-agent` package with the `httpAgent` config key. Creating the agent once and sharing it across requests is critical because each agent maintains its own connection pool to the proxy.

Axios interceptors provide a powerful mechanism for proxy-aware request processing. Register a request interceptor that dynamically selects proxy agents for different target domains, and a response interceptor that detects proxy-related failures (like 407 auth errors) and retries with refreshed credentials. This interceptor pattern keeps your business logic clean while centralizing all proxy management in a reusable module.

Common Pitfalls

The most confusing aspect of Axios proxy configuration is the difference between the `proxy` config option and the agent-based approach. Axios's built-in `proxy` option only works for HTTP targets and is overridden by the `HTTP_PROXY` environment variable. For HTTPS destinations, which are the vast majority of modern websites, you must use the agent approach. Mixing the two approaches leads to requests that bypass the proxy entirely or fail with cryptic TLS errors.

Memory leaks from unclosed agents are another risk in long-running Node.js services. If you create a new `HttpsProxyAgent` for each request instead of reusing one, each agent opens its own connection pool and the old pools may not be garbage collected promptly. This slowly consumes file descriptors until the process crashes with EMFILE errors. Always instantiate your agent at the module level or in a singleton pattern.

Performance Optimization

Maximize Axios throughput by tuning the agent's underlying socket pool. The `https-proxy-agent` respects Node.js's `maxSockets` and `keepAlive` options. Set `keepAlive: true` and `maxSockets: 50` to maintain up to 50 persistent connections to the proxy gateway. This eliminates the TCP/TLS handshake overhead that adds 100-200ms per request when connections are not reused.

For batch operations, use `Promise.allSettled()` instead of `Promise.all()` to process results even when some proxied requests fail. Implement a request queue with concurrency limiting using a library like `p-limit` to prevent overwhelming the proxy with thousands of simultaneous connections. Monitor your Node.js process with `process.memoryUsage()` and the `--max-old-space-size` flag to ensure memory consumption stays stable during extended proxy crawling sessions.

Tips

  • 1
    Use https-proxy-agent for HTTPS destinations through HTTP proxies.
  • 2
    Share the agent instance across requests to reuse connections.
  • 3
    Set axios timeout separately from the agent timeout for layered protection.

Ready to Integrate?

Get proxy credentials and start coding in minutes.