An HTTP(s) proxy http.Agent implementation for HTTP requests through proxy servers
npx @tessl/cli install tessl/npm-http-proxy-agent@7.0.0HTTP Proxy Agent provides an HTTP(s) proxy
http.Agenthttp.Agentnpm install http-proxy-agentimport { HttpProxyAgent, type HttpProxyAgentOptions } from "http-proxy-agent";For CommonJS:
const { HttpProxyAgent } = require("http-proxy-agent");
// Note: HttpProxyAgentOptions is a TypeScript-only type exportimport * 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);
});HTTP Proxy Agent extends the
Agentagent-baseThe 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;// 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];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;
}HTTP Proxy Agent handles several error scenarios:
ECONNREFUSED407 Proxy Authentication Requiredimport { 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'
});