CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-http-proxy-agent

An HTTP(s) proxy http.Agent implementation for HTTP requests through proxy servers

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

HTTP Proxy Agent

HTTP Proxy Agent provides an HTTP(s) proxy http.Agent implementation for Node.js that routes HTTP requests through specified HTTP or HTTPS proxy servers. It extends Node.js's built-in http.Agent with proxy connectivity, authentication support, and custom header capabilities.

Package Information

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

Core Imports

import { HttpProxyAgent, type HttpProxyAgentOptions } from "http-proxy-agent";

For CommonJS:

const { HttpProxyAgent } = require("http-proxy-agent");
// Note: HttpProxyAgentOptions is a TypeScript-only type export

Basic Usage

import * as http from 'http';
import { HttpProxyAgent } from 'http-proxy-agent';

// Create proxy agent
const agent = new HttpProxyAgent('http://168.63.76.32:3128');

// Use with http module
http.get('http://nodejs.org/api/', { agent }, (res) => {
  console.log('"response" event!', res.headers);
  res.pipe(process.stdout);
});

Architecture

HTTP Proxy Agent extends the Agent class from the agent-base package to provide:

  • Proxy Connection Management: Establishes connections to HTTP/HTTPS proxy servers
  • Request Modification: Transforms client requests to work through proxy servers
  • Authentication Handling: Automatic Basic authentication from proxy URL credentials
  • Header Management: Configurable custom headers sent to proxy servers
  • Protocol Support: Works with both HTTP and HTTPS proxy servers

Capabilities

HttpProxyAgent Class

The main export that implements an HTTP Agent subclass for proxy connections.

// Required imports for type definitions
import { Agent, AgentConnectOpts } from 'agent-base';
import { OutgoingHttpHeaders } from 'http';
import * as net from 'net';
import * as tls from 'tls';
import { URL } from 'url';

/**
 * HTTP Agent subclass that connects to specified HTTP proxy server to proxy HTTP requests.
 * Extends Agent from agent-base package which provides HTTP/HTTPS agent functionality.
 */
class HttpProxyAgent<Uri extends string> extends Agent {
  /** Supported proxy protocols */
  static readonly protocols: ['http', 'https'];
  
  /** The proxy server URL */
  readonly proxy: URL;
  
  /** Headers to send to proxy server (static object or dynamic function) */
  proxyHeaders: OutgoingHttpHeaders | (() => OutgoingHttpHeaders);
  
  /** Connection options for proxy socket */
  connectOpts: net.TcpNetConnectOpts & tls.ConnectionOptions;

  /** 
   * Default port for the target server (inherited from Agent base class)
   * Used when no port is specified in the request URL
   */
  defaultPort: number;

  /**
   * Create new HttpProxyAgent instance
   * @param proxy - Proxy server URL string (Uri generic ensures string type) or URL object
   * @param opts - Agent options including headers and connection settings
   */
  constructor(proxy: Uri | URL, opts?: HttpProxyAgentOptions<Uri>);

  /**
   * Add request to agent with proxy-specific modifications
   * Internal method called by Node.js http module
   * @param req - HTTP client request (with internal properties)
   * @param opts - Agent connection options
   */
  addRequest(req: HttpProxyAgentClientRequest, opts: AgentConnectOpts): void;

  /**
   * Set request properties for proxy routing
   * Modifies the request path to full URL for proxy forwarding
   * @param req - HTTP client request
   * @param opts - Agent connection options  
   */
  setRequestProps(req: HttpProxyAgentClientRequest, opts: AgentConnectOpts): void;

  /**
   * Connect to proxy server and return socket
   * Creates TCP or TLS connection to proxy server based on proxy protocol
   * @param req - HTTP client request
   * @param opts - Agent connection options
   * @returns Promise resolving to connected socket
   */
  connect(req: HttpProxyAgentClientRequest, opts: AgentConnectOpts): Promise<net.Socket>;
}

Usage Examples:

import { HttpProxyAgent } from 'http-proxy-agent';

// Basic HTTP proxy (Uri generic inferred as string)
const agent = new HttpProxyAgent('http://proxy.example.com:8080');

// HTTPS proxy  
const httpsAgent = new HttpProxyAgent('https://proxy.example.com:8080');

// Proxy with authentication embedded in URL
const authAgent = new HttpProxyAgent('http://user:pass@proxy.example.com:8080');

// Using URL object instead of string
const proxyUrl = new URL('http://proxy.example.com:8080');
const urlAgent = new HttpProxyAgent(proxyUrl);

// Proxy with custom headers
const headerAgent = new HttpProxyAgent('http://proxy.example.com:8080', {
  headers: { 'Custom-Header': 'value' }
});

// Proxy with dynamic headers function
const dynamicAgent = new HttpProxyAgent('http://proxy.example.com:8080', {
  headers: () => ({ 'Timestamp': Date.now().toString() })
});

// Proxy with keep-alive connection reuse
const keepAliveAgent = new HttpProxyAgent('http://proxy.example.com:8080', {
  keepAlive: true
});

// HTTPS proxy with custom TLS options
const tlsAgent = new HttpProxyAgent('https://proxy.example.com:8080', {
  rejectUnauthorized: false,
  ca: [], // custom CA certificates array
});

// Setting defaultPort property (inherited from Agent)
agent.defaultPort = 8080;

Exported Types

HttpProxyAgentOptions (exported)

// Required imports for this type
import { OutgoingHttpHeaders } from 'http';
import * as http from 'http';
import * as net from 'net';
import * as tls from 'tls';

/**
 * Options for HttpProxyAgent constructor (exported as type)
 * Combines connection options, HTTP agent options, and proxy-specific headers
 */
export type HttpProxyAgentOptions<T> = ConnectOpts<T> & http.AgentOptions & {
  /** 
   * Additional headers to send to proxy server in each request
   * Can be static object or function returning headers object
   * NOTE: If proxy doesn't strip headers, they're also sent to destination
   */
  headers?: OutgoingHttpHeaders | (() => OutgoingHttpHeaders);
};

// Supporting types for HttpProxyAgentOptions
type Protocol<T> = T extends `${infer Protocol}:${infer _}` ? Protocol : never;

type ConnectOptsMap = {
  http: Omit<net.TcpNetConnectOpts, 'host' | 'port'>;
  https: Omit<tls.ConnectionOptions, 'host' | 'port'>;
};

type ConnectOpts<T> = {
  [P in keyof ConnectOptsMap]: Protocol<T> extends P
    ? ConnectOptsMap[P]
    : never;
}[keyof ConnectOptsMap];

Internal Types

These types are used internally but not exported:

// Required imports for internal types
import * as http from 'http';

/** Extended http.ClientRequest with internal properties (internal use only) */
interface HttpProxyAgentClientRequest extends http.ClientRequest {
  /** Internal Node.js property - output buffer data */
  outputData?: {
    data: string;
  }[];
  /** Internal Node.js property - cached header string */
  _header?: string | null;
  /** Internal Node.js method - generates HTTP header string */
  _implicitHeader(): void;
}

Error Handling

HTTP Proxy Agent handles several error scenarios:

  • Connection Errors: ECONNREFUSED when proxy server is unreachable
  • Authentication Errors: 407 Proxy Authentication Required response when credentials are invalid
  • Protocol Errors: Automatic protocol detection and appropriate socket creation (net.Socket vs tls.Socket)
import { HttpProxyAgent } from 'http-proxy-agent';
import * as http from 'http';

const agent = new HttpProxyAgent('http://invalid-proxy:4');

http.get('http://example.com', { agent }, (res) => {
  // This won't be reached due to connection error
}).on('error', (err) => {
  console.error('Request failed:', err.code); // 'ECONNREFUSED'
});

Platform Support

  • Node.js: >= 14
  • Module Systems: CommonJS and ES modules
  • Protocols: HTTP and HTTPS proxy servers
  • Authentication: Basic authentication via URL credentials
  • TLS: Full TLS configuration support for HTTPS proxies
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/http-proxy-agent@7.0.x
Publish Source
CLI
Badge
tessl/npm-http-proxy-agent badge