An HTTP(s) proxy http.Agent implementation for HTTP requests through proxy servers
npx @tessl/cli install tessl/npm-http-proxy-agent@7.0.00
# HTTP Proxy Agent
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: http-proxy-agent
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install http-proxy-agent`
10
11
## Core Imports
12
13
```typescript
14
import { HttpProxyAgent, type HttpProxyAgentOptions } from "http-proxy-agent";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { HttpProxyAgent } = require("http-proxy-agent");
21
// Note: HttpProxyAgentOptions is a TypeScript-only type export
22
```
23
24
## Basic Usage
25
26
```typescript
27
import * as http from 'http';
28
import { HttpProxyAgent } from 'http-proxy-agent';
29
30
// Create proxy agent
31
const agent = new HttpProxyAgent('http://168.63.76.32:3128');
32
33
// Use with http module
34
http.get('http://nodejs.org/api/', { agent }, (res) => {
35
console.log('"response" event!', res.headers);
36
res.pipe(process.stdout);
37
});
38
```
39
40
## Architecture
41
42
HTTP Proxy Agent extends the `Agent` class from the `agent-base` package to provide:
43
44
- **Proxy Connection Management**: Establishes connections to HTTP/HTTPS proxy servers
45
- **Request Modification**: Transforms client requests to work through proxy servers
46
- **Authentication Handling**: Automatic Basic authentication from proxy URL credentials
47
- **Header Management**: Configurable custom headers sent to proxy servers
48
- **Protocol Support**: Works with both HTTP and HTTPS proxy servers
49
50
## Capabilities
51
52
### HttpProxyAgent Class
53
54
The main export that implements an HTTP Agent subclass for proxy connections.
55
56
```typescript { .api }
57
// Required imports for type definitions
58
import { Agent, AgentConnectOpts } from 'agent-base';
59
import { OutgoingHttpHeaders } from 'http';
60
import * as net from 'net';
61
import * as tls from 'tls';
62
import { URL } from 'url';
63
64
/**
65
* HTTP Agent subclass that connects to specified HTTP proxy server to proxy HTTP requests.
66
* Extends Agent from agent-base package which provides HTTP/HTTPS agent functionality.
67
*/
68
class HttpProxyAgent<Uri extends string> extends Agent {
69
/** Supported proxy protocols */
70
static readonly protocols: ['http', 'https'];
71
72
/** The proxy server URL */
73
readonly proxy: URL;
74
75
/** Headers to send to proxy server (static object or dynamic function) */
76
proxyHeaders: OutgoingHttpHeaders | (() => OutgoingHttpHeaders);
77
78
/** Connection options for proxy socket */
79
connectOpts: net.TcpNetConnectOpts & tls.ConnectionOptions;
80
81
/**
82
* Default port for the target server (inherited from Agent base class)
83
* Used when no port is specified in the request URL
84
*/
85
defaultPort: number;
86
87
/**
88
* Create new HttpProxyAgent instance
89
* @param proxy - Proxy server URL string (Uri generic ensures string type) or URL object
90
* @param opts - Agent options including headers and connection settings
91
*/
92
constructor(proxy: Uri | URL, opts?: HttpProxyAgentOptions<Uri>);
93
94
/**
95
* Add request to agent with proxy-specific modifications
96
* Internal method called by Node.js http module
97
* @param req - HTTP client request (with internal properties)
98
* @param opts - Agent connection options
99
*/
100
addRequest(req: HttpProxyAgentClientRequest, opts: AgentConnectOpts): void;
101
102
/**
103
* Set request properties for proxy routing
104
* Modifies the request path to full URL for proxy forwarding
105
* @param req - HTTP client request
106
* @param opts - Agent connection options
107
*/
108
setRequestProps(req: HttpProxyAgentClientRequest, opts: AgentConnectOpts): void;
109
110
/**
111
* Connect to proxy server and return socket
112
* Creates TCP or TLS connection to proxy server based on proxy protocol
113
* @param req - HTTP client request
114
* @param opts - Agent connection options
115
* @returns Promise resolving to connected socket
116
*/
117
connect(req: HttpProxyAgentClientRequest, opts: AgentConnectOpts): Promise<net.Socket>;
118
}
119
```
120
121
**Usage Examples:**
122
123
```typescript
124
import { HttpProxyAgent } from 'http-proxy-agent';
125
126
// Basic HTTP proxy (Uri generic inferred as string)
127
const agent = new HttpProxyAgent('http://proxy.example.com:8080');
128
129
// HTTPS proxy
130
const httpsAgent = new HttpProxyAgent('https://proxy.example.com:8080');
131
132
// Proxy with authentication embedded in URL
133
const authAgent = new HttpProxyAgent('http://user:pass@proxy.example.com:8080');
134
135
// Using URL object instead of string
136
const proxyUrl = new URL('http://proxy.example.com:8080');
137
const urlAgent = new HttpProxyAgent(proxyUrl);
138
139
// Proxy with custom headers
140
const headerAgent = new HttpProxyAgent('http://proxy.example.com:8080', {
141
headers: { 'Custom-Header': 'value' }
142
});
143
144
// Proxy with dynamic headers function
145
const dynamicAgent = new HttpProxyAgent('http://proxy.example.com:8080', {
146
headers: () => ({ 'Timestamp': Date.now().toString() })
147
});
148
149
// Proxy with keep-alive connection reuse
150
const keepAliveAgent = new HttpProxyAgent('http://proxy.example.com:8080', {
151
keepAlive: true
152
});
153
154
// HTTPS proxy with custom TLS options
155
const tlsAgent = new HttpProxyAgent('https://proxy.example.com:8080', {
156
rejectUnauthorized: false,
157
ca: [], // custom CA certificates array
158
});
159
160
// Setting defaultPort property (inherited from Agent)
161
agent.defaultPort = 8080;
162
```
163
164
165
## Exported Types
166
167
### HttpProxyAgentOptions (exported)
168
169
```typescript { .api }
170
// Required imports for this type
171
import { OutgoingHttpHeaders } from 'http';
172
import * as http from 'http';
173
import * as net from 'net';
174
import * as tls from 'tls';
175
176
/**
177
* Options for HttpProxyAgent constructor (exported as type)
178
* Combines connection options, HTTP agent options, and proxy-specific headers
179
*/
180
export type HttpProxyAgentOptions<T> = ConnectOpts<T> & http.AgentOptions & {
181
/**
182
* Additional headers to send to proxy server in each request
183
* Can be static object or function returning headers object
184
* NOTE: If proxy doesn't strip headers, they're also sent to destination
185
*/
186
headers?: OutgoingHttpHeaders | (() => OutgoingHttpHeaders);
187
};
188
189
// Supporting types for HttpProxyAgentOptions
190
type Protocol<T> = T extends `${infer Protocol}:${infer _}` ? Protocol : never;
191
192
type ConnectOptsMap = {
193
http: Omit<net.TcpNetConnectOpts, 'host' | 'port'>;
194
https: Omit<tls.ConnectionOptions, 'host' | 'port'>;
195
};
196
197
type ConnectOpts<T> = {
198
[P in keyof ConnectOptsMap]: Protocol<T> extends P
199
? ConnectOptsMap[P]
200
: never;
201
}[keyof ConnectOptsMap];
202
```
203
204
## Internal Types
205
206
These types are used internally but not exported:
207
208
```typescript { .api }
209
// Required imports for internal types
210
import * as http from 'http';
211
212
/** Extended http.ClientRequest with internal properties (internal use only) */
213
interface HttpProxyAgentClientRequest extends http.ClientRequest {
214
/** Internal Node.js property - output buffer data */
215
outputData?: {
216
data: string;
217
}[];
218
/** Internal Node.js property - cached header string */
219
_header?: string | null;
220
/** Internal Node.js method - generates HTTP header string */
221
_implicitHeader(): void;
222
}
223
```
224
225
## Error Handling
226
227
HTTP Proxy Agent handles several error scenarios:
228
229
- **Connection Errors**: `ECONNREFUSED` when proxy server is unreachable
230
- **Authentication Errors**: `407 Proxy Authentication Required` response when credentials are invalid
231
- **Protocol Errors**: Automatic protocol detection and appropriate socket creation (net.Socket vs tls.Socket)
232
233
```typescript
234
import { HttpProxyAgent } from 'http-proxy-agent';
235
import * as http from 'http';
236
237
const agent = new HttpProxyAgent('http://invalid-proxy:4');
238
239
http.get('http://example.com', { agent }, (res) => {
240
// This won't be reached due to connection error
241
}).on('error', (err) => {
242
console.error('Request failed:', err.code); // 'ECONNREFUSED'
243
});
244
```
245
246
## Platform Support
247
248
- **Node.js**: >= 14
249
- **Module Systems**: CommonJS and ES modules
250
- **Protocols**: HTTP and HTTPS proxy servers
251
- **Authentication**: Basic authentication via URL credentials
252
- **TLS**: Full TLS configuration support for HTTPS proxies