or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-proxy-agent

Maps proxy protocols to http.Agent implementations

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/proxy-agent@6.5.x

To install, run

npx @tessl/cli install tessl/npm-proxy-agent@6.5.0

index.mddocs/

Proxy Agent

Proxy Agent provides an HTTP Agent implementation that automatically uses proxy servers based on environment variables. It maps various proxy protocols (HTTP, HTTPS, SOCKS4/5, PAC) to their corresponding proxy agent implementations, using an LRU cache for efficient agent reuse.

Package Information

  • Package Name: proxy-agent
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install proxy-agent

Core Imports

import { ProxyAgent, proxies } from "proxy-agent";
import type { ProxyAgentOptions } from "proxy-agent";

For CommonJS:

const { ProxyAgent, proxies } = require("proxy-agent");

Basic Usage

import * as https from 'https';
import { ProxyAgent } from 'proxy-agent';

// The correct proxy Agent implementation to use will be determined
// via the http_proxy / https_proxy / no_proxy / etc. env vars
const agent = new ProxyAgent();

// The rest works just like any other normal HTTP request
https.get('https://jsonip.com', { agent }, (res) => {
  console.log(res.statusCode, res.headers);
  res.pipe(process.stdout);
});

Architecture

Proxy Agent is built around several key components:

  • Environment Variable Detection: Uses the proxy-from-env module to determine proxy configuration from standard environment variables
  • Protocol Mapping: Maps proxy protocols to their appropriate agent implementations with lazy loading
  • LRU Caching: Maintains a cache of agent instances for efficient reuse across requests
  • Agent Selection: Dynamically selects the appropriate proxy agent based on request type and proxy protocol

Capabilities

ProxyAgent Class

Main HTTP Agent implementation that extends the Agent class from agent-base. Automatically detects and uses proxy servers based on environment variables.

/**
 * Uses the appropriate Agent subclass based off of the "proxy"
 * environment variables that are currently set.
 * An LRU cache is used, to prevent unnecessary creation of proxy
 * http.Agent instances.
 */
class ProxyAgent extends Agent {
  constructor(opts?: ProxyAgentOptions);
  
  /** Cache for Agent instances */
  cache: LRUCache<string, Agent>;
  
  /** Stored connection options */
  connectOpts?: ProxyAgentOptions;
  
  /** Default HTTP agent for non-proxy requests */
  httpAgent: http.Agent;
  
  /** Default HTTPS agent for non-proxy requests */
  httpsAgent: http.Agent;
  
  /** Function to determine proxy for given URL */
  getProxyForUrl: GetProxyForUrlCallback;
  
  /**
   * Main connection method that selects appropriate agent based on proxy configuration
   * @param req - The HTTP request
   * @param opts - Connection options from agent-base
   * @returns Promise resolving to the appropriate agent for the request
   */
  connect(req: http.ClientRequest, opts: AgentConnectOpts): Promise<http.Agent>;
  
  /**
   * Destroys all cached agents and cleans up resources
   */
  destroy(): void;
}

Usage Examples:

import { ProxyAgent } from 'proxy-agent';

// Basic usage with environment variables
const agent = new ProxyAgent();

// With custom options
const agent = new ProxyAgent({
  keepAlive: true,
  timeout: 5000,
  rejectUnauthorized: false
});

// With custom proxy resolution
const agent = new ProxyAgent({
  getProxyForUrl: (url, req) => {
    // Custom logic to determine proxy
    return 'http://my-proxy.com:8080';
  }
});

// Access the cache
console.log(`Current cache size: ${agent.cache.size}`);

// Cleanup when done
agent.destroy();

Constructor Options

Configuration options for creating a ProxyAgent instance.

interface ProxyAgentOptions extends 
  HttpProxyAgentOptions<''>,
  HttpsProxyAgentOptions<''>,
  SocksProxyAgentOptions,
  PacProxyAgentOptions<''> {
  
  /**
   * Default http.Agent instance to use when no proxy is
   * configured for a request. Defaults to a new http.Agent()
   * instance with the proxy agent options passed in.
   */
  httpAgent?: http.Agent;
  
  /**
   * Default https.Agent instance to use when no proxy is
   * configured for a request. Defaults to a new https.Agent()
   * instance with the proxy agent options passed in.
   */
  httpsAgent?: http.Agent;
  
  /**
   * A callback for dynamic provision of proxy for url.
   * Defaults to standard proxy environment variables,
   * see https://www.npmjs.com/package/proxy-from-env for details
   */
  getProxyForUrl?: GetProxyForUrlCallback;
}

Proxy Resolution Callback

Function type for custom proxy URL resolution.

/**
 * Function type for custom proxy URL resolution
 * @param url - The target URL being requested
 * @param req - The HTTP client request object
 * @returns Proxy URL string, or empty string for no proxy, or Promise resolving to same
 */
interface GetProxyForUrlCallback {
  (url: string, req: http.ClientRequest): string | Promise<string>;
}

Protocol Mapping Configuration

Exported constant that maps proxy protocols to their corresponding agent constructors. This is primarily for advanced usage or integration purposes.

/**
 * Exported constant mapping proxy protocols to agent constructors
 * [0] = constructor for HTTP requests
 * [1] = constructor for HTTPS/WebSocket requests
 */
export const proxies: {
  [P in ValidProtocol]: [
    () => Promise<AgentConstructor>,
    () => Promise<AgentConstructor>
  ];
};

type ValidProtocol = 
  | 'http'     // HTTP proxy: http://proxy-server.com:3128
  | 'https'    // HTTPS proxy: https://proxy-server.com:3129
  | 'socks'    // SOCKS5 proxy: socks://username:password@proxy.com:9050
  | 'socks4'   // SOCKS4 proxy: socks4://proxy.com:9050
  | 'socks4a'  // SOCKS4A proxy: socks4a://proxy.com:9050
  | 'socks5'   // SOCKS5 proxy: socks5://username:password@proxy.com:9050
  | 'socks5h'  // SOCKS5 with hostname resolution: socks5h://proxy.com:9050
  | 'pac+data' // PAC with data URL: pac+data:application/x-ns-proxy-autoconfig;base64,...
  | 'pac+file' // PAC with file URL: pac+file:///path/to/proxy.pac
  | 'pac+ftp'  // PAC with FTP URL: pac+ftp://server/proxy.pac
  | 'pac+http' // PAC with HTTP URL: pac+http://server/proxy.pac
  | 'pac+https'; // PAC with HTTPS URL: pac+https://server/proxy.pac

Environment Variables

The package automatically respects standard proxy environment variables:

  • HTTP_PROXY - Proxy for HTTP requests
  • HTTPS_PROXY - Proxy for HTTPS requests
  • WS_PROXY - Proxy for WebSocket requests
  • WSS_PROXY - Proxy for secure WebSocket requests
  • NO_PROXY - Comma-separated list of URLs to exclude from proxying
  • ALL_PROXY - Fallback proxy for all protocols

Example configuration:

export HTTP_PROXY=http://proxy.company.com:8080
export HTTPS_PROXY=https://secure-proxy.company.com:8443
export NO_PROXY=localhost,127.0.0.1,.company.com

Types

// Re-exported from dependencies for convenience
import type { Agent, AgentConnectOpts } from 'agent-base';
import type { PacProxyAgentOptions } from 'pac-proxy-agent';
import type { HttpProxyAgentOptions } from 'http-proxy-agent';
import type { HttpsProxyAgentOptions } from 'https-proxy-agent';
import type { SocksProxyAgentOptions } from 'socks-proxy-agent';

/**
 * Constructor type for proxy agent implementations
 */
interface AgentConstructor {
  new (proxy: string, proxyAgentOptions?: ProxyAgentOptions): Agent;
}

Error Handling

The ProxyAgent will throw errors in the following cases:

  • Unsupported Protocol: When an unsupported proxy protocol is encountered

    // Throws: "Unsupported protocol for proxy URL: ftp://proxy.com"
  • Invalid Proxy URL: When the proxy URL cannot be parsed

  • Connection Failures: Standard HTTP/HTTPS connection errors from underlying agents

Common error handling pattern:

import { ProxyAgent } from 'proxy-agent';
import * as https from 'https';

const agent = new ProxyAgent();

const request = https.get('https://api.example.com', { agent }, (res) => {
  // Handle response
});

request.on('error', (err) => {
  if (err.message.includes('Unsupported protocol')) {
    console.error('Invalid proxy configuration:', err.message);
  } else {
    console.error('Request failed:', err.message);
  }
});