← Back to Hex Proxies

Node.js Proxy Setup

Configure HTTP proxies in Node.js with axios, node-fetch, and undici. Complete proxy setup guide with Hex Proxies.

Requirements

  • Node.js 18+
  • npm or yarn
  • https-proxy-agent package

Installation

npm install https-proxy-agent

Code Example

import axios from 'axios';
import { HttpsProxyAgent } from 'https-proxy-agent';

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

// Axios with proxy agent
const response = await axios.get('https://httpbin.org/ip', {
  httpsAgent: agent,
  timeout: 30000,
});
console.log(response.data);

// Native fetch with undici ProxyAgent
import { ProxyAgent, fetch as undiciFetch } from 'undici';

const proxyAgent = new ProxyAgent(
  'http://user:pass@gate.hexproxies.com:8080'
);
const res = await undiciFetch('https://httpbin.org/ip', {
  dispatcher: proxyAgent,
});
console.log(await res.json());

Setup Steps

1

Install the proxy agent

Run npm install https-proxy-agent to add CONNECT tunnel support to Node.js HTTP clients.

2

Create the agent instance

Instantiate HttpsProxyAgent with your Hex Proxies gateway URL including credentials.

3

Attach to your HTTP client

Pass the agent as httpsAgent to axios or as dispatcher to undici fetch.

4

Verify with httpbin

Request httpbin.org/ip and confirm the returned IP is from the Hex Proxies pool.

5

Configure error handling

Add axios interceptors or try/catch blocks to handle ECONNREFUSED, ETIMEDOUT, and 407 errors.

6

Externalize credentials

Read the proxy URL from process.env.PROXY_URL using dotenv or your deployment config.

Configuration Options

OptionDescription
Proxy URLhttp://user:pass@gate.hexproxies.com:8080 -- passed to HttpsProxyAgent constructor.
TimeoutSet timeout: 30000 on axios config. Use AbortController for undici/fetch.
Max SocketsLimit concurrent connections with maxSockets on the agent to avoid overwhelming destinations.
Keep-AliveEnabled by default. Reuses TCP connections across requests for lower latency.
TLS VerificationKeep rejectUnauthorized: true. Only disable for local testing with self-signed certs.

Best Practices

  • Reuse a single HttpsProxyAgent instance across requests for connection pooling and lower latency.
  • Store proxy credentials in process.env, never commit them to version control.
  • Set maxSockets on the agent to limit concurrent connections and prevent destination-side rate limiting.
  • Use axios-retry or p-retry for automatic retry with exponential backoff on transient errors.
  • For IP rotation, create a new agent instance per request or use Hex Proxies session parameters.
  • Prefer undici ProxyAgent on Node 18+ for best throughput without third-party dependencies.
  • Log request duration and status codes per proxy request to detect degradation early.
  • Set explicit timeouts on every request; Node.js defaults to no timeout which can leak sockets.

Node.js Proxy Setup

Node.js does not include built-in proxy support in its HTTP client. Unlike Python where you pass a dictionary, Node.js requires an agent object that intercepts outgoing connections and routes them through the proxy tunnel. The https-proxy-agent package is the standard solution, compatible with axios, node-fetch, and the native http/https modules.

Starting with Node.js 18, the built-in undici module offers a ProxyAgent dispatcher that works with the global fetch API. This eliminates the need for third-party packages in modern Node.js environments, though https-proxy-agent remains necessary for axios and older codebases.

Prerequisites

Before you begin, make sure you have: - An active Hex Proxies account with proxy credentials - Node.js 18+ - npm or yarn - https-proxy-agent package

Installation

npm install https-proxy-agent

Basic Proxy Configuration

Create an HttpsProxyAgent instance with your Hex Proxies gateway URL. This agent handles CONNECT tunneling, credential negotiation, and keep-alive management automatically.

import axios from 'axios';
import { HttpsProxyAgent } from 'https-proxy-agent';

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

// Axios with proxy agent
const response = await axios.get('https://httpbin.org/ip', {
  httpsAgent: agent,
  timeout: 30000,
});
console.log(response.data);

// Native fetch with undici ProxyAgent
import { ProxyAgent, fetch as undiciFetch } from 'undici';

const proxyAgent = new ProxyAgent(
  'http://user:pass@gate.hexproxies.com:8080'
);
const res = await undiciFetch('https://httpbin.org/ip', {
  dispatcher: proxyAgent,
});
console.log(await res.json());

Agent Reuse and Connection Pooling

A single HttpsProxyAgent instance maintains an internal connection pool. Reuse the same agent across multiple axios requests to avoid repeated TCP handshakes to the proxy gateway. Creating a new agent per request wastes 20-40ms on connection setup each time.

Axios vs Undici vs node-fetch

Axios provides the most familiar API with interceptors, automatic JSON parsing, and request cancellation. Undici is the fastest option with zero dependencies (bundled in Node 18+). node-fetch mirrors the browser Fetch API but requires the separate https-proxy-agent package. Choose based on your existing codebase.

Configuration Options

  • Proxy URL -- http://user:pass@gate.hexproxies.com:8080 passed to the agent constructor.
  • Timeout -- Set timeout: 30000 on axios or AbortController with setTimeout for fetch.
  • Keep-Alive -- The agent enables keep-alive by default. Set keepAlive: false only if you need a fresh connection per request.
  • Max Sockets -- Defaults to Infinity. Set maxSockets: 50 on the agent to limit concurrent proxy connections.
  • TLS Options -- Pass rejectUnauthorized: true (default) in the agent options. Never disable TLS verification in production.

Error Handling

Node.js proxy errors surface as specific error codes that require distinct handling strategies.

Common errors and solutions:

1. ECONNREFUSED
   - The proxy gateway rejected the connection or is unreachable
   - Verify gate.hexproxies.com:8080 resolves and is not blocked by a firewall
   - Check if your IP is whitelisted on the Hex Proxies dashboard

2. ETIMEDOUT / ESOCKETTIMEDOUT
   - Connection to the proxy or destination timed out
   - Increase axios timeout from 30000 to 60000 for slow destinations
   - Implement retry with axios-retry or custom interceptor

3. HPE_INVALID_CONSTANT (Parse Error)
   - The proxy returned a malformed HTTP response
   - Usually caused by the destination sending non-HTTP content
   - Add response validation before parsing

4. 407 Proxy Authentication Required
   - Credentials in the agent URL are incorrect
   - Ensure username and password are URL-encoded for special characters
   - Verify subscription status on the Hex Proxies dashboard

5. ECONNRESET
   - The proxy or destination closed the connection unexpectedly
   - Retry with a new agent instance to get a fresh connection
   - For persistent resets, switch to a different proxy pool region

Use axios interceptors or try/catch with async/await to handle errors consistently across your application.

Error Handling

Node.js proxy errors surface as specific error codes that require distinct handling strategies.

Common errors and solutions:

1. ECONNREFUSED
   - The proxy gateway rejected the connection or is unreachable
   - Verify gate.hexproxies.com:8080 resolves and is not blocked by a firewall
   - Check if your IP is whitelisted on the Hex Proxies dashboard

2. ETIMEDOUT / ESOCKETTIMEDOUT
   - Connection to the proxy or destination timed out
   - Increase axios timeout from 30000 to 60000 for slow destinations
   - Implement retry with axios-retry or custom interceptor

3. HPE_INVALID_CONSTANT (Parse Error)
   - The proxy returned a malformed HTTP response
   - Usually caused by the destination sending non-HTTP content
   - Add response validation before parsing

4. 407 Proxy Authentication Required
   - Credentials in the agent URL are incorrect
   - Ensure username and password are URL-encoded for special characters
   - Verify subscription status on the Hex Proxies dashboard

5. ECONNRESET
   - The proxy or destination closed the connection unexpectedly
   - Retry with a new agent instance to get a fresh connection
   - For persistent resets, switch to a different proxy pool region

Use axios interceptors or try/catch with async/await to handle errors consistently across your application.

Frequently Asked Questions

Does Node.js have built-in proxy support?

No. You need https-proxy-agent for axios/node-fetch, or use undici ProxyAgent which ships with Node.js 18+ for the global fetch API.

How do I use proxies with axios in Node.js?

Create an HttpsProxyAgent and pass it as the httpsAgent option in your axios request config or axios.create() defaults.

Should I create one agent or many?

Reuse a single agent instance for connection pooling. Create separate agents only when you need different proxy credentials or rotation behavior per request group.

How do I handle proxy authentication in Node.js?

Embed credentials in the proxy URL: http://user:pass@gate.hexproxies.com:8080. URL-encode special characters in the password.

Ready to Get Started?

Set up Node.js with Hex Proxies in minutes.