0
# Proxy Agent
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: proxy-agent
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install proxy-agent`
10
11
## Core Imports
12
13
```typescript
14
import { ProxyAgent, proxies } from "proxy-agent";
15
import type { ProxyAgentOptions } from "proxy-agent";
16
```
17
18
For CommonJS:
19
20
```javascript
21
const { ProxyAgent, proxies } = require("proxy-agent");
22
```
23
24
## Basic Usage
25
26
```typescript
27
import * as https from 'https';
28
import { ProxyAgent } from 'proxy-agent';
29
30
// The correct proxy Agent implementation to use will be determined
31
// via the http_proxy / https_proxy / no_proxy / etc. env vars
32
const agent = new ProxyAgent();
33
34
// The rest works just like any other normal HTTP request
35
https.get('https://jsonip.com', { agent }, (res) => {
36
console.log(res.statusCode, res.headers);
37
res.pipe(process.stdout);
38
});
39
```
40
41
## Architecture
42
43
Proxy Agent is built around several key components:
44
45
- **Environment Variable Detection**: Uses the `proxy-from-env` module to determine proxy configuration from standard environment variables
46
- **Protocol Mapping**: Maps proxy protocols to their appropriate agent implementations with lazy loading
47
- **LRU Caching**: Maintains a cache of agent instances for efficient reuse across requests
48
- **Agent Selection**: Dynamically selects the appropriate proxy agent based on request type and proxy protocol
49
50
## Capabilities
51
52
### ProxyAgent Class
53
54
Main HTTP Agent implementation that extends the `Agent` class from `agent-base`. Automatically detects and uses proxy servers based on environment variables.
55
56
```typescript { .api }
57
/**
58
* Uses the appropriate Agent subclass based off of the "proxy"
59
* environment variables that are currently set.
60
* An LRU cache is used, to prevent unnecessary creation of proxy
61
* http.Agent instances.
62
*/
63
class ProxyAgent extends Agent {
64
constructor(opts?: ProxyAgentOptions);
65
66
/** Cache for Agent instances */
67
cache: LRUCache<string, Agent>;
68
69
/** Stored connection options */
70
connectOpts?: ProxyAgentOptions;
71
72
/** Default HTTP agent for non-proxy requests */
73
httpAgent: http.Agent;
74
75
/** Default HTTPS agent for non-proxy requests */
76
httpsAgent: http.Agent;
77
78
/** Function to determine proxy for given URL */
79
getProxyForUrl: GetProxyForUrlCallback;
80
81
/**
82
* Main connection method that selects appropriate agent based on proxy configuration
83
* @param req - The HTTP request
84
* @param opts - Connection options from agent-base
85
* @returns Promise resolving to the appropriate agent for the request
86
*/
87
connect(req: http.ClientRequest, opts: AgentConnectOpts): Promise<http.Agent>;
88
89
/**
90
* Destroys all cached agents and cleans up resources
91
*/
92
destroy(): void;
93
}
94
```
95
96
**Usage Examples:**
97
98
```typescript
99
import { ProxyAgent } from 'proxy-agent';
100
101
// Basic usage with environment variables
102
const agent = new ProxyAgent();
103
104
// With custom options
105
const agent = new ProxyAgent({
106
keepAlive: true,
107
timeout: 5000,
108
rejectUnauthorized: false
109
});
110
111
// With custom proxy resolution
112
const agent = new ProxyAgent({
113
getProxyForUrl: (url, req) => {
114
// Custom logic to determine proxy
115
return 'http://my-proxy.com:8080';
116
}
117
});
118
119
// Access the cache
120
console.log(`Current cache size: ${agent.cache.size}`);
121
122
// Cleanup when done
123
agent.destroy();
124
```
125
126
### Constructor Options
127
128
Configuration options for creating a ProxyAgent instance.
129
130
```typescript { .api }
131
interface ProxyAgentOptions extends
132
HttpProxyAgentOptions<''>,
133
HttpsProxyAgentOptions<''>,
134
SocksProxyAgentOptions,
135
PacProxyAgentOptions<''> {
136
137
/**
138
* Default http.Agent instance to use when no proxy is
139
* configured for a request. Defaults to a new http.Agent()
140
* instance with the proxy agent options passed in.
141
*/
142
httpAgent?: http.Agent;
143
144
/**
145
* Default https.Agent instance to use when no proxy is
146
* configured for a request. Defaults to a new https.Agent()
147
* instance with the proxy agent options passed in.
148
*/
149
httpsAgent?: http.Agent;
150
151
/**
152
* A callback for dynamic provision of proxy for url.
153
* Defaults to standard proxy environment variables,
154
* see https://www.npmjs.com/package/proxy-from-env for details
155
*/
156
getProxyForUrl?: GetProxyForUrlCallback;
157
}
158
```
159
160
### Proxy Resolution Callback
161
162
Function type for custom proxy URL resolution.
163
164
```typescript { .api }
165
/**
166
* Function type for custom proxy URL resolution
167
* @param url - The target URL being requested
168
* @param req - The HTTP client request object
169
* @returns Proxy URL string, or empty string for no proxy, or Promise resolving to same
170
*/
171
interface GetProxyForUrlCallback {
172
(url: string, req: http.ClientRequest): string | Promise<string>;
173
}
174
```
175
176
### Protocol Mapping Configuration
177
178
Exported constant that maps proxy protocols to their corresponding agent constructors. This is primarily for advanced usage or integration purposes.
179
180
```typescript { .api }
181
/**
182
* Exported constant mapping proxy protocols to agent constructors
183
* [0] = constructor for HTTP requests
184
* [1] = constructor for HTTPS/WebSocket requests
185
*/
186
export const proxies: {
187
[P in ValidProtocol]: [
188
() => Promise<AgentConstructor>,
189
() => Promise<AgentConstructor>
190
];
191
};
192
193
type ValidProtocol =
194
| 'http' // HTTP proxy: http://proxy-server.com:3128
195
| 'https' // HTTPS proxy: https://proxy-server.com:3129
196
| 'socks' // SOCKS5 proxy: socks://username:password@proxy.com:9050
197
| 'socks4' // SOCKS4 proxy: socks4://proxy.com:9050
198
| 'socks4a' // SOCKS4A proxy: socks4a://proxy.com:9050
199
| 'socks5' // SOCKS5 proxy: socks5://username:password@proxy.com:9050
200
| 'socks5h' // SOCKS5 with hostname resolution: socks5h://proxy.com:9050
201
| 'pac+data' // PAC with data URL: pac+data:application/x-ns-proxy-autoconfig;base64,...
202
| 'pac+file' // PAC with file URL: pac+file:///path/to/proxy.pac
203
| 'pac+ftp' // PAC with FTP URL: pac+ftp://server/proxy.pac
204
| 'pac+http' // PAC with HTTP URL: pac+http://server/proxy.pac
205
| 'pac+https'; // PAC with HTTPS URL: pac+https://server/proxy.pac
206
```
207
208
## Environment Variables
209
210
The package automatically respects standard proxy environment variables:
211
212
- **HTTP_PROXY** - Proxy for HTTP requests
213
- **HTTPS_PROXY** - Proxy for HTTPS requests
214
- **WS_PROXY** - Proxy for WebSocket requests
215
- **WSS_PROXY** - Proxy for secure WebSocket requests
216
- **NO_PROXY** - Comma-separated list of URLs to exclude from proxying
217
- **ALL_PROXY** - Fallback proxy for all protocols
218
219
Example configuration:
220
221
```bash
222
export HTTP_PROXY=http://proxy.company.com:8080
223
export HTTPS_PROXY=https://secure-proxy.company.com:8443
224
export NO_PROXY=localhost,127.0.0.1,.company.com
225
```
226
227
## Types
228
229
```typescript { .api }
230
// Re-exported from dependencies for convenience
231
import type { Agent, AgentConnectOpts } from 'agent-base';
232
import type { PacProxyAgentOptions } from 'pac-proxy-agent';
233
import type { HttpProxyAgentOptions } from 'http-proxy-agent';
234
import type { HttpsProxyAgentOptions } from 'https-proxy-agent';
235
import type { SocksProxyAgentOptions } from 'socks-proxy-agent';
236
237
/**
238
* Constructor type for proxy agent implementations
239
*/
240
interface AgentConstructor {
241
new (proxy: string, proxyAgentOptions?: ProxyAgentOptions): Agent;
242
}
243
```
244
245
## Error Handling
246
247
The ProxyAgent will throw errors in the following cases:
248
249
- **Unsupported Protocol**: When an unsupported proxy protocol is encountered
250
```typescript
251
// Throws: "Unsupported protocol for proxy URL: ftp://proxy.com"
252
```
253
254
- **Invalid Proxy URL**: When the proxy URL cannot be parsed
255
- **Connection Failures**: Standard HTTP/HTTPS connection errors from underlying agents
256
257
Common error handling pattern:
258
259
```typescript
260
import { ProxyAgent } from 'proxy-agent';
261
import * as https from 'https';
262
263
const agent = new ProxyAgent();
264
265
const request = https.get('https://api.example.com', { agent }, (res) => {
266
// Handle response
267
});
268
269
request.on('error', (err) => {
270
if (err.message.includes('Unsupported protocol')) {
271
console.error('Invalid proxy configuration:', err.message);
272
} else {
273
console.error('Request failed:', err.message);
274
}
275
});
276
```