0
# Core HTTP APIs
1
2
High-performance HTTP request methods optimized for different use cases, from simple requests to complex streaming scenarios.
3
4
## Capabilities
5
6
### request
7
8
Promise-based HTTP requests with the highest performance. Ideal for most HTTP client needs.
9
10
```javascript { .api }
11
/**
12
* Performs an HTTP request with high performance
13
* @param url - The URL to request
14
* @param options - Request configuration options
15
* @returns Promise resolving to response data
16
*/
17
function request(url: string | URL, options?: RequestOptions): Promise<ResponseData>;
18
19
interface RequestOptions {
20
method?: string;
21
headers?: IncomingHttpHeaders;
22
body?: BodyInit;
23
query?: Record<string, any>;
24
idempotent?: boolean;
25
blocking?: boolean;
26
upgrade?: boolean;
27
headersTimeout?: number;
28
bodyTimeout?: number;
29
reset?: boolean;
30
throwOnError?: boolean;
31
expectContinue?: boolean;
32
signal?: AbortSignal;
33
opaque?: unknown;
34
}
35
36
interface ResponseData {
37
statusCode: number;
38
headers: IncomingHttpHeaders;
39
body: BodyReadable;
40
trailers: Record<string, string>;
41
opaque: unknown;
42
context: {
43
history: readonly URL[];
44
};
45
}
46
```
47
48
**Usage Examples:**
49
50
```javascript
51
import { request } from 'undici';
52
53
// Simple GET request
54
const { statusCode, headers, body } = await request('https://api.example.com/users');
55
const users = await body.json();
56
57
// POST request with JSON body
58
const response = await request('https://api.example.com/users', {
59
method: 'POST',
60
headers: {
61
'content-type': 'application/json'
62
},
63
body: JSON.stringify({ name: 'Alice', email: 'alice@example.com' })
64
});
65
66
// Request with timeout and error handling
67
try {
68
const { body } = await request('https://slow-api.example.com/data', {
69
headersTimeout: 5000,
70
bodyTimeout: 10000,
71
throwOnError: true
72
});
73
const data = await body.json();
74
} catch (error) {
75
console.error('Request failed:', error.message);
76
}
77
```
78
79
### stream
80
81
Streaming HTTP requests for handling large payloads efficiently with backpressure support.
82
83
```javascript { .api }
84
/**
85
* Performs a streaming HTTP request
86
* @param url - The URL to request
87
* @param options - Request configuration options
88
* @param factory - Factory function to create the stream handler
89
* @returns Promise resolving to stream data
90
*/
91
function stream(
92
url: string | URL,
93
options: RequestOptions,
94
factory: StreamFactory
95
): Promise<StreamData>;
96
97
type StreamFactory = (data: StreamFactoryData) => Writable;
98
99
interface StreamFactoryData {
100
statusCode: number;
101
headers: IncomingHttpHeaders;
102
opaque: unknown;
103
}
104
105
interface StreamData {
106
opaque: unknown;
107
trailers: Record<string, string>;
108
}
109
```
110
111
**Usage Examples:**
112
113
```javascript
114
import { stream } from 'undici';
115
import { createWriteStream } from 'fs';
116
117
// Download large file
118
await stream('https://example.com/large-file.zip', {}, ({ statusCode, headers }) => {
119
if (statusCode === 200) {
120
return createWriteStream('./large-file.zip');
121
}
122
throw new Error(`Request failed with status ${statusCode}`);
123
});
124
125
// Stream processing with custom writable
126
await stream('https://api.example.com/stream-data', {
127
method: 'GET',
128
headers: { 'accept': 'application/json' }
129
}, ({ statusCode }) => {
130
return new Writable({
131
write(chunk, encoding, callback) {
132
// Process each chunk of data
133
const data = JSON.parse(chunk.toString());
134
console.log('Received:', data);
135
callback();
136
}
137
});
138
});
139
```
140
141
### pipeline
142
143
Pipeline HTTP requests with Node.js streams for maximum control over data flow.
144
145
```javascript { .api }
146
/**
147
* Creates a pipeline for streaming HTTP requests
148
* @param url - The URL to request
149
* @param options - Request configuration options
150
* @param handler - Pipeline handler for processing the stream
151
* @returns Duplex stream for the pipeline
152
*/
153
function pipeline(
154
url: string | URL,
155
options: PipelineOptions,
156
handler: PipelineHandler
157
): Duplex;
158
159
interface PipelineOptions extends RequestOptions {
160
objectMode?: boolean;
161
}
162
163
type PipelineHandler = (data: PipelineHandlerData) => Readable | Transform;
164
165
interface PipelineHandlerData {
166
statusCode: number;
167
headers: IncomingHttpHeaders;
168
opaque: unknown;
169
body: BodyReadable;
170
}
171
```
172
173
**Usage Examples:**
174
175
```javascript
176
import { pipeline } from 'undici';
177
import { Transform } from 'stream';
178
import { createReadStream, createWriteStream } from 'fs';
179
180
// Upload file with transformation
181
const uploadStream = pipeline('https://api.example.com/upload', {
182
method: 'POST',
183
headers: { 'content-type': 'application/octet-stream' }
184
}, ({ statusCode }) => {
185
if (statusCode !== 200) {
186
throw new Error(`Upload failed: ${statusCode}`);
187
}
188
return new Transform({
189
transform(chunk, encoding, callback) {
190
// Process upload response
191
callback(null, chunk);
192
}
193
});
194
});
195
196
// Pipe file through upload
197
createReadStream('./file.txt').pipe(uploadStream).pipe(process.stdout);
198
```
199
200
### connect
201
202
HTTP CONNECT method for establishing tunnels, typically used for proxying.
203
204
```javascript { .api }
205
/**
206
* Establishes an HTTP CONNECT tunnel
207
* @param url - The URL to connect to
208
* @param options - Connection options
209
* @returns Promise resolving to connection data
210
*/
211
function connect(url: string | URL, options?: ConnectOptions): Promise<ConnectData>;
212
213
interface ConnectOptions {
214
headers?: IncomingHttpHeaders;
215
signal?: AbortSignal;
216
opaque?: unknown;
217
}
218
219
interface ConnectData {
220
statusCode: number;
221
headers: IncomingHttpHeaders;
222
socket: Duplex;
223
opaque: unknown;
224
}
225
```
226
227
**Usage Examples:**
228
229
```javascript
230
import { connect } from 'undici';
231
232
// Establish CONNECT tunnel through proxy
233
const { socket, statusCode } = await connect('https://proxy.example.com:8080', {
234
headers: {
235
'proxy-authorization': 'Basic ' + Buffer.from('user:pass').toString('base64')
236
}
237
});
238
239
if (statusCode === 200) {
240
// Use socket for tunneled communication
241
socket.write('GET /api/data HTTP/1.1\r\nHost: api.example.com\r\n\r\n');
242
socket.on('data', (chunk) => {
243
console.log(chunk.toString());
244
});
245
}
246
```
247
248
### upgrade
249
250
HTTP protocol upgrade requests for switching protocols (e.g., WebSocket handshake).
251
252
```javascript { .api }
253
/**
254
* Performs an HTTP protocol upgrade
255
* @param url - The URL to upgrade
256
* @param options - Upgrade options
257
* @returns Promise resolving to upgrade data
258
*/
259
function upgrade(url: string | URL, options?: UpgradeOptions): Promise<UpgradeData>;
260
261
interface UpgradeOptions {
262
headers?: IncomingHttpHeaders;
263
protocol?: string;
264
signal?: AbortSignal;
265
opaque?: unknown;
266
}
267
268
interface UpgradeData {
269
headers: IncomingHttpHeaders;
270
socket: Duplex;
271
opaque: unknown;
272
}
273
```
274
275
**Usage Examples:**
276
277
```javascript
278
import { upgrade } from 'undici';
279
280
// WebSocket handshake
281
const { socket, headers } = await upgrade('ws://localhost:3000/socket', {
282
headers: {
283
'upgrade': 'websocket',
284
'connection': 'upgrade',
285
'sec-websocket-key': 'dGhlIHNhbXBsZSBub25jZQ==',
286
'sec-websocket-version': '13'
287
}
288
});
289
290
// Handle WebSocket communication
291
socket.on('data', (data) => {
292
console.log('WebSocket data:', data);
293
});
294
```
295
296
## Types
297
298
### Body Types
299
300
```javascript { .api }
301
type BodyInit =
302
| ArrayBuffer
303
| AsyncIterable<Uint8Array>
304
| Blob
305
| FormData
306
| Iterable<Uint8Array>
307
| NodeJS.ArrayBufferView
308
| URLSearchParams
309
| null
310
| string;
311
312
interface BodyReadable extends Readable {
313
arrayBuffer(): Promise<ArrayBuffer>;
314
blob(): Promise<Blob>;
315
bytes(): Promise<Uint8Array>;
316
json(): Promise<any>;
317
text(): Promise<string>;
318
}
319
```
320
321
### Header Types
322
323
```javascript { .api }
324
type IncomingHttpHeaders = Record<string, string | string[]>;
325
type OutgoingHttpHeaders = Record<string, string | string[] | number>;
326
```