0
# Connection Management
1
2
Advanced connection pooling, load balancing, and proxy support for high-performance applications. These components provide sophisticated routing and connection management capabilities.
3
4
## Capabilities
5
6
### Proxy Agent
7
8
HTTP proxy support with authentication and custom configuration.
9
10
```typescript { .api }
11
/**
12
* HTTP proxy agent supporting HTTP and HTTPS proxies
13
* Handles proxy authentication and connection management
14
*/
15
class ProxyAgent extends Dispatcher {
16
constructor(options: ProxyAgent.Options);
17
18
readonly closed: boolean;
19
readonly destroyed: boolean;
20
}
21
22
interface ProxyAgent.Options {
23
/** Proxy server URI */
24
uri: string;
25
26
/** Proxy authentication token */
27
token?: string;
28
29
/** Proxy authentication (alternative to token) */
30
auth?: string;
31
32
/** Request timeout in milliseconds */
33
requestTimeout?: number;
34
35
/** Connection timeout in milliseconds */
36
connectionTimeout?: number;
37
38
/** Headers to send with proxy requests */
39
headers?: Record<string, string>;
40
41
/** Dispatcher factory for creating upstream connections */
42
factory?: (origin: URL, opts: object) => Dispatcher;
43
}
44
```
45
46
**Usage Examples:**
47
48
```typescript
49
import { ProxyAgent, request } from "undici-types";
50
51
// Basic proxy agent
52
const proxyAgent = new ProxyAgent({
53
uri: "http://proxy.example.com:8080"
54
});
55
56
// Proxy with authentication
57
const authProxyAgent = new ProxyAgent({
58
uri: "http://proxy.example.com:8080",
59
auth: "username:password"
60
});
61
62
// Proxy with bearer token
63
const tokenProxyAgent = new ProxyAgent({
64
uri: "https://proxy.example.com:8080",
65
token: "Bearer your-token-here",
66
requestTimeout: 30000,
67
headers: {
68
"User-Agent": "MyApp/1.0"
69
}
70
});
71
72
// Use proxy for requests
73
const response = await request("https://api.example.com/data", {
74
dispatcher: proxyAgent
75
});
76
77
// Set as global dispatcher
78
import { setGlobalDispatcher } from "undici-types";
79
setGlobalDispatcher(proxyAgent);
80
```
81
82
### Environment HTTP Proxy Agent
83
84
Automatic proxy configuration from environment variables.
85
86
```typescript { .api }
87
/**
88
* HTTP proxy agent that automatically configures from environment variables
89
* Reads HTTP_PROXY, HTTPS_PROXY, and NO_PROXY environment variables
90
*/
91
class EnvHttpProxyAgent extends Dispatcher {
92
constructor(options?: EnvHttpProxyAgent.Options);
93
94
readonly closed: boolean;
95
readonly destroyed: boolean;
96
}
97
98
interface EnvHttpProxyAgent.Options {
99
/** Request timeout in milliseconds */
100
requestTimeout?: number;
101
102
/** Connection timeout in milliseconds */
103
connectionTimeout?: number;
104
105
/** Headers to send with proxy requests */
106
headers?: Record<string, string>;
107
108
/** Dispatcher factory for creating upstream connections */
109
factory?: (origin: URL, opts: object) => Dispatcher;
110
}
111
```
112
113
**Usage Examples:**
114
115
```typescript
116
import { EnvHttpProxyAgent, setGlobalDispatcher } from "undici-types";
117
118
// Set environment variables (typically done by the system)
119
// HTTP_PROXY=http://proxy.example.com:8080
120
// HTTPS_PROXY=https://secure-proxy.example.com:8080
121
// NO_PROXY=localhost,127.0.0.1,.example.com
122
123
// Create agent that reads environment
124
const envProxyAgent = new EnvHttpProxyAgent({
125
requestTimeout: 30000,
126
connectionTimeout: 10000
127
});
128
129
// Set as global dispatcher for automatic proxy usage
130
setGlobalDispatcher(envProxyAgent);
131
132
// All requests now use environment-configured proxy
133
const response1 = await request("https://api.example.com/data"); // Uses HTTPS_PROXY
134
const response2 = await request("http://api.example.com/data"); // Uses HTTP_PROXY
135
const response3 = await request("https://localhost:3000/data"); // Bypassed (NO_PROXY)
136
```
137
138
### Retry Agent
139
140
Agent with automatic retry capabilities for failed requests.
141
142
```typescript { .api }
143
/**
144
* Agent with automatic retry capabilities
145
* Handles transient failures with configurable retry strategies
146
*/
147
class RetryAgent extends Dispatcher {
148
constructor(dispatcher: Dispatcher, options?: RetryAgent.Options);
149
150
readonly closed: boolean;
151
readonly destroyed: boolean;
152
}
153
154
interface RetryAgent.Options {
155
/** Maximum number of retry attempts */
156
retry?: number;
157
158
/** Maximum timeout for retry attempts in milliseconds */
159
maxTimeout?: number;
160
161
/** Minimum timeout between retries in milliseconds */
162
minTimeout?: number;
163
164
/** Timeout multiplier for exponential backoff */
165
timeoutFactor?: number;
166
167
/** Maximum delay between retries in milliseconds */
168
maxRetryAfter?: number;
169
170
/** HTTP methods to retry */
171
methods?: HttpMethod[];
172
173
/** HTTP status codes to retry */
174
statusCodes?: number[];
175
176
/** Error codes to retry */
177
errorCodes?: string[];
178
179
/** Custom retry condition function */
180
retryAfter?: boolean;
181
}
182
183
type HttpMethod = "GET" | "HEAD" | "OPTIONS" | "PUT" | "DELETE" | "TRACE";
184
```
185
186
**Usage Examples:**
187
188
```typescript
189
import { RetryAgent, Agent } from "undici-types";
190
191
// Create base agent
192
const baseAgent = new Agent({
193
connections: 100
194
});
195
196
// Wrap with retry capabilities
197
const retryAgent = new RetryAgent(baseAgent, {
198
retry: 3,
199
maxTimeout: 30000,
200
minTimeout: 1000,
201
timeoutFactor: 2,
202
methods: ["GET", "HEAD", "OPTIONS", "PUT", "DELETE"],
203
statusCodes: [408, 413, 429, 500, 502, 503, 504],
204
errorCodes: ["ECONNRESET", "ECONNREFUSED", "ENOTFOUND", "ENETDOWN"]
205
});
206
207
// Requests automatically retry on failure
208
const response = await retryAgent.request({
209
path: "/api/unreliable-endpoint",
210
method: "GET",
211
origin: "https://api.example.com"
212
});
213
214
// Custom retry logic
215
const customRetryAgent = new RetryAgent(baseAgent, {
216
retry: 5,
217
retryAfter: true, // Respect Retry-After headers
218
maxRetryAfter: 30000,
219
statusCodes: [429, 500, 502, 503, 504]
220
});
221
```
222
223
### Snapshot Agent
224
225
Agent for capturing and replaying HTTP interactions.
226
227
```typescript { .api }
228
/**
229
* Agent for snapshot testing and HTTP interaction recording
230
* Captures requests and responses for testing scenarios
231
*/
232
class SnapshotAgent extends Dispatcher {
233
constructor(options?: SnapshotAgent.Options);
234
235
readonly closed: boolean;
236
readonly destroyed: boolean;
237
238
/** Capture snapshot of HTTP interactions */
239
capture(): SnapshotAgent.Snapshot;
240
241
/** Restore from snapshot */
242
restore(snapshot: SnapshotAgent.Snapshot): void;
243
244
/** Clear recorded interactions */
245
clear(): void;
246
}
247
248
interface SnapshotAgent.Options {
249
/** Base dispatcher for actual requests */
250
dispatcher?: Dispatcher;
251
252
/** Recording mode */
253
mode?: "record" | "replay" | "passthrough";
254
255
/** Snapshot storage path */
256
snapshotPath?: string;
257
258
/** Whether to update snapshots */
259
updateSnapshot?: boolean;
260
}
261
262
interface SnapshotAgent.Snapshot {
263
interactions: Array<{
264
request: {
265
method: string;
266
url: string;
267
headers: Record<string, string>;
268
body?: string;
269
};
270
response: {
271
status: number;
272
headers: Record<string, string>;
273
body: string;
274
};
275
}>;
276
timestamp: string;
277
version: string;
278
}
279
```
280
281
**Usage Examples:**
282
283
```typescript
284
import { SnapshotAgent } from "undici-types";
285
286
// Recording mode - captures real HTTP interactions
287
const recordingAgent = new SnapshotAgent({
288
mode: "record",
289
snapshotPath: "./snapshots/api-interactions.json"
290
});
291
292
// Make requests that get recorded
293
await recordingAgent.request({
294
origin: "https://api.example.com",
295
path: "/users",
296
method: "GET"
297
});
298
299
await recordingAgent.request({
300
origin: "https://api.example.com",
301
path: "/posts",
302
method: "GET"
303
});
304
305
// Capture the recorded interactions
306
const snapshot = recordingAgent.capture();
307
308
// Replay mode - replays captured interactions
309
const replayAgent = new SnapshotAgent({
310
mode: "replay",
311
snapshotPath: "./snapshots/api-interactions.json"
312
});
313
314
// Restore from snapshot
315
replayAgent.restore(snapshot);
316
317
// These requests return recorded responses
318
const usersResponse = await replayAgent.request({
319
origin: "https://api.example.com",
320
path: "/users",
321
method: "GET"
322
});
323
324
const postsResponse = await replayAgent.request({
325
origin: "https://api.example.com",
326
path: "/posts",
327
method: "GET"
328
});
329
```
330
331
### Connection Builder
332
333
Low-level connection building utilities for custom connection logic.
334
335
```typescript { .api }
336
/**
337
* Build custom connection function for clients
338
* @param options - Connection building options
339
* @returns Connection function
340
*/
341
function buildConnector(options?: buildConnector.Options): buildConnector.connector;
342
343
namespace buildConnector {
344
interface Options {
345
/** Maximum number of cached sessions */
346
maxCachedSessions?: number;
347
348
/** Socket path for Unix domain sockets */
349
socketPath?: string;
350
351
/** Connection timeout in milliseconds */
352
timeout?: number;
353
354
/** Keep alive timeout in milliseconds */
355
keepAlive?: number;
356
357
/** Keep alive initial delay in milliseconds */
358
keepAliveInitialDelay?: number;
359
360
/** TLS connection options */
361
tls?: TLSSocket.Options;
362
363
/** Whether to allow half-open connections */
364
allowHalfOpen?: boolean;
365
}
366
367
interface connector {
368
(options: {
369
hostname: string;
370
host?: string;
371
protocol: string;
372
port: string;
373
servername?: string;
374
localAddress?: string;
375
httpSocket?: Socket;
376
}, callback: (error: Error | null, socket?: Socket | TLSSocket) => void): void;
377
}
378
379
interface TLSSocket extends Socket {
380
authorized: boolean;
381
authorizationError?: Error;
382
encrypted: boolean;
383
getCertificate(): PeerCertificate | null;
384
getPeerCertificate(detailed?: boolean): PeerCertificate | null;
385
getSession(): Buffer | null;
386
getTLSTicket(): Buffer | null;
387
renegotiate(options: object, callback: (err: Error | null) => void): boolean;
388
setMaxSendFragment(size: number): boolean;
389
}
390
}
391
```
392
393
**Usage Examples:**
394
395
```typescript
396
import { buildConnector, Client } from "undici-types";
397
398
// Custom connector with Unix socket
399
const unixConnector = buildConnector({
400
socketPath: "/var/run/app.sock",
401
timeout: 10000
402
});
403
404
const unixClient = new Client("http://localhost", {
405
connect: unixConnector
406
});
407
408
// Custom connector with TLS options
409
const tlsConnector = buildConnector({
410
timeout: 15000,
411
keepAlive: true,
412
keepAliveInitialDelay: 1000,
413
tls: {
414
rejectUnauthorized: false,
415
ca: customCertificate,
416
cert: clientCertificate,
417
key: clientKey
418
}
419
});
420
421
const secureClient = new Client("https://secure.example.com", {
422
connect: tlsConnector
423
});
424
425
// Custom connector with connection caching
426
const cachingConnector = buildConnector({
427
maxCachedSessions: 100,
428
timeout: 30000,
429
keepAlive: true
430
});
431
432
const cachingClient = new Client("https://api.example.com", {
433
connect: cachingConnector
434
});
435
```
436
437
## Advanced Configuration
438
439
### Global Origin Management
440
441
```typescript { .api }
442
/**
443
* Set global origin for relative URL resolution
444
* @param origin - The base origin URL
445
*/
446
function setGlobalOrigin(origin: string | URL): void;
447
448
/**
449
* Get the current global origin
450
* @returns Current global origin or undefined
451
*/
452
function getGlobalOrigin(): string | undefined;
453
```
454
455
### Global Dispatcher Management
456
457
```typescript { .api }
458
/**
459
* Set the global dispatcher for all HTTP operations
460
* @param dispatcher - The dispatcher to use globally
461
*/
462
function setGlobalDispatcher(dispatcher: Dispatcher): void;
463
464
/**
465
* Get the current global dispatcher
466
* @returns Current global dispatcher
467
*/
468
function getGlobalDispatcher(): Dispatcher;
469
```
470
471
**Usage Examples:**
472
473
```typescript
474
import {
475
setGlobalDispatcher,
476
setGlobalOrigin,
477
ProxyAgent,
478
RetryAgent,
479
Agent
480
} from "undici-types";
481
482
// Set up sophisticated global configuration
483
const baseAgent = new Agent({ connections: 200 });
484
const proxyAgent = new ProxyAgent({
485
uri: process.env.HTTP_PROXY || "http://proxy.company.com:8080"
486
});
487
const retryAgent = new RetryAgent(proxyAgent, {
488
retry: 3,
489
methods: ["GET", "HEAD", "PUT", "DELETE"]
490
});
491
492
// Configure global settings
493
setGlobalDispatcher(retryAgent);
494
setGlobalOrigin("https://api.company.com");
495
496
// All requests now use proxy + retry + connection pooling
497
const response = await request("/users"); // Relative URL resolved with global origin
498
```