0
# Headers Management
1
2
HTTP header manipulation with case-insensitive operations and Web Standards compatibility. The Headers class provides a comprehensive interface for managing HTTP headers in both requests and responses.
3
4
## Capabilities
5
6
### Headers Class
7
8
Manages HTTP headers with case-insensitive operations and various initialization options.
9
10
```javascript { .api }
11
/**
12
* HTTP Headers class for manipulating request and response headers
13
*/
14
class Headers {
15
constructor(init?: HeadersInit);
16
17
// Core methods
18
append(name: string, value: string): void;
19
delete(name: string): void;
20
get(name: string): string | null;
21
has(name: string): boolean;
22
set(name: string, value: string): void;
23
24
// Iteration methods
25
forEach(callback: (value: string, key: string, headers: Headers) => void, thisArg?: any): void;
26
entries(): IterableIterator<[string, string]>;
27
keys(): IterableIterator<string>;
28
values(): IterableIterator<string>;
29
[Symbol.iterator](): IterableIterator<[string, string]>;
30
31
// Node.js extension
32
raw(): Record<string, string[]>;
33
}
34
35
type HeadersInit = Headers | Record<string, string> | Iterable<readonly [string, string]> | Iterable<Iterable<string>>;
36
```
37
38
**Usage Examples:**
39
40
```javascript
41
import { Headers } from 'node-fetch';
42
43
// Create empty headers
44
const headers = new Headers();
45
46
// Create from object
47
const headers = new Headers({
48
'Content-Type': 'application/json',
49
'Authorization': 'Bearer token123'
50
});
51
52
// Create from array of pairs
53
const headers = new Headers([
54
['Content-Type', 'application/json'],
55
['X-Custom-Header', 'value']
56
]);
57
58
// Create from existing Headers instance
59
const existingHeaders = new Headers({ 'Accept': 'application/json' });
60
const newHeaders = new Headers(existingHeaders);
61
```
62
63
### Header Manipulation
64
65
Methods for adding, modifying, and removing HTTP headers.
66
67
```javascript { .api }
68
interface HeaderManipulation {
69
/**
70
* Adds a value to an existing header or creates a new header
71
* @param name - Header name (case-insensitive)
72
* @param value - Header value to append
73
*/
74
append(name: string, value: string): void;
75
76
/**
77
* Removes a header entirely
78
* @param name - Header name to remove (case-insensitive)
79
*/
80
delete(name: string): void;
81
82
/**
83
* Gets the value of a header
84
* @param name - Header name (case-insensitive)
85
* @returns Header value or null if not found
86
*/
87
get(name: string): string | null;
88
89
/**
90
* Checks if a header exists
91
* @param name - Header name (case-insensitive)
92
* @returns True if header exists
93
*/
94
has(name: string): boolean;
95
96
/**
97
* Sets a header value, replacing any existing value
98
* @param name - Header name (case-insensitive)
99
* @param value - Header value to set
100
*/
101
set(name: string, value: string): void;
102
}
103
```
104
105
**Usage Examples:**
106
107
```javascript
108
const headers = new Headers();
109
110
// Set headers
111
headers.set('Content-Type', 'application/json');
112
headers.set('Authorization', 'Bearer token123');
113
114
// Append to existing header (creates comma-separated values)
115
headers.append('Accept', 'application/json');
116
headers.append('Accept', 'application/xml');
117
console.log(headers.get('Accept')); // 'application/json, application/xml'
118
119
// Check if header exists
120
if (headers.has('Authorization')) {
121
console.log('Authorization header is present');
122
}
123
124
// Get header value
125
const contentType = headers.get('Content-Type');
126
console.log(contentType); // 'application/json'
127
128
// Delete header
129
headers.delete('Authorization');
130
console.log(headers.has('Authorization')); // false
131
132
// Case-insensitive operations
133
headers.set('content-type', 'text/plain');
134
console.log(headers.get('Content-Type')); // 'text/plain'
135
```
136
137
### Header Iteration
138
139
Methods for iterating over headers with support for modern JavaScript iteration patterns.
140
141
```javascript { .api }
142
interface HeaderIteration {
143
/**
144
* Executes a callback for each header
145
* @param callback - Function to execute for each header
146
* @param thisArg - Value to use as 'this' when executing callback
147
*/
148
forEach(callback: (value: string, key: string, headers: Headers) => void, thisArg?: any): void;
149
150
/**
151
* Returns an iterator for [name, value] pairs
152
*/
153
entries(): IterableIterator<[string, string]>;
154
155
/**
156
* Returns an iterator for header names
157
*/
158
keys(): IterableIterator<string>;
159
160
/**
161
* Returns an iterator for header values
162
*/
163
values(): IterableIterator<string>;
164
165
/**
166
* Default iterator (same as entries())
167
*/
168
[Symbol.iterator](): IterableIterator<[string, string]>;
169
}
170
```
171
172
**Usage Examples:**
173
174
```javascript
175
const headers = new Headers({
176
'Content-Type': 'application/json',
177
'Authorization': 'Bearer token123',
178
'X-Custom-Header': 'custom-value'
179
});
180
181
// Use forEach
182
headers.forEach((value, name) => {
183
console.log(`${name}: ${value}`);
184
});
185
186
// Use for...of with entries
187
for (const [name, value] of headers.entries()) {
188
console.log(`${name}: ${value}`);
189
}
190
191
// Use for...of with default iterator
192
for (const [name, value] of headers) {
193
console.log(`${name}: ${value}`);
194
}
195
196
// Iterate over keys
197
for (const name of headers.keys()) {
198
console.log(`Header name: ${name}`);
199
}
200
201
// Iterate over values
202
for (const value of headers.values()) {
203
console.log(`Header value: ${value}`);
204
}
205
206
// Convert to array
207
const headerArray = [...headers.entries()];
208
const headerNames = [...headers.keys()];
209
const headerValues = [...headers.values()];
210
```
211
212
### Raw Headers Access
213
214
Node.js specific extension for accessing raw header values as arrays.
215
216
```javascript { .api }
217
interface RawHeaders {
218
/**
219
* Returns raw headers as an object with arrays of values
220
* @returns Object mapping header names to arrays of values
221
*/
222
raw(): Record<string, string[]>;
223
}
224
```
225
226
**Usage Examples:**
227
228
```javascript
229
const headers = new Headers();
230
headers.append('Accept', 'application/json');
231
headers.append('Accept', 'application/xml');
232
headers.append('Set-Cookie', 'session=abc123');
233
headers.append('Set-Cookie', 'theme=dark');
234
235
// Get raw headers (useful for Set-Cookie and similar headers)
236
const rawHeaders = headers.raw();
237
console.log(rawHeaders);
238
// {
239
// 'accept': ['application/json', 'application/xml'],
240
// 'set-cookie': ['session=abc123', 'theme=dark']
241
// }
242
243
// Access individual cookie values
244
const cookies = headers.raw()['set-cookie'];
245
cookies.forEach(cookie => {
246
console.log('Cookie:', cookie);
247
});
248
```
249
250
### Common Header Patterns
251
252
Examples of working with common HTTP headers in typical scenarios.
253
254
```javascript { .api }
255
// Common content types
256
type ContentType =
257
| 'application/json'
258
| 'application/x-www-form-urlencoded'
259
| 'multipart/form-data'
260
| 'text/plain'
261
| 'text/html'
262
| 'application/octet-stream';
263
264
// Common authentication patterns
265
type AuthHeader =
266
| `Bearer ${string}`
267
| `Basic ${string}`
268
| `Digest ${string}`;
269
```
270
271
**Usage Examples:**
272
273
```javascript
274
// JSON API headers
275
const jsonHeaders = new Headers({
276
'Content-Type': 'application/json',
277
'Accept': 'application/json',
278
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIs...'
279
});
280
281
// Form submission headers
282
const formHeaders = new Headers({
283
'Content-Type': 'application/x-www-form-urlencoded'
284
});
285
286
// File upload headers (multipart is set automatically by FormData)
287
const uploadHeaders = new Headers({
288
'Authorization': 'Bearer token123'
289
// Content-Type will be set automatically when using FormData
290
});
291
292
// Basic authentication
293
const credentials = btoa('username:password');
294
const authHeaders = new Headers({
295
'Authorization': `Basic ${credentials}`
296
});
297
298
// Custom headers for API versioning
299
const apiHeaders = new Headers({
300
'Accept': 'application/vnd.api+json',
301
'X-API-Version': '2.1',
302
'X-Client-ID': 'myapp-v1.0'
303
});
304
305
// Cache control headers
306
const cacheHeaders = new Headers({
307
'Cache-Control': 'no-cache, no-store, must-revalidate',
308
'Pragma': 'no-cache',
309
'Expires': '0'
310
});
311
```
312
313
### Headers in Requests and Responses
314
315
How headers work with Request and Response objects.
316
317
```javascript { .api }
318
interface RequestWithHeaders {
319
readonly headers: Headers;
320
}
321
322
interface ResponseWithHeaders {
323
readonly headers: Headers;
324
}
325
```
326
327
**Usage Examples:**
328
329
```javascript
330
import fetch, { Request, Response, Headers } from 'node-fetch';
331
332
// Using headers with Request
333
const requestHeaders = new Headers({
334
'User-Agent': 'MyApp/1.0',
335
'Accept': 'application/json'
336
});
337
338
const request = new Request('https://api.example.com/data', {
339
method: 'GET',
340
headers: requestHeaders
341
});
342
343
// Access request headers
344
console.log(request.headers.get('User-Agent')); // 'MyApp/1.0'
345
346
// Using headers with fetch
347
const response = await fetch('https://api.example.com/data', {
348
headers: {
349
'Authorization': 'Bearer token123',
350
'Accept': 'application/json'
351
}
352
});
353
354
// Access response headers
355
console.log(response.headers.get('Content-Type'));
356
console.log(response.headers.get('Server'));
357
console.log(response.headers.get('Date'));
358
359
// Get all Set-Cookie headers (common pattern)
360
const setCookieHeaders = response.headers.raw()['set-cookie'] || [];
361
setCookieHeaders.forEach(cookie => {
362
console.log('Set-Cookie:', cookie);
363
});
364
```
365
366
### Header Validation
367
368
Headers class automatically validates header names and values according to HTTP specifications.
369
370
```javascript { .api }
371
interface HeaderValidation {
372
// Throws TypeError for invalid header names or values
373
validateHeaderName(name: string): void;
374
validateHeaderValue(name: string, value: string): void;
375
}
376
```
377
378
**Usage Examples:**
379
380
```javascript
381
const headers = new Headers();
382
383
try {
384
// Valid headers
385
headers.set('Content-Type', 'application/json');
386
headers.set('X-Custom-Header', 'valid-value');
387
388
// Invalid header name (will throw TypeError)
389
headers.set('Invalid Header Name', 'value'); // Spaces not allowed
390
391
} catch (error) {
392
console.error('Invalid header:', error.message);
393
// Error: Header name must be a valid HTTP token [Invalid Header Name]
394
}
395
396
try {
397
// Invalid header value (will throw TypeError)
398
headers.set('Custom-Header', 'value\nwith\nnewlines'); // Control characters not allowed
399
400
} catch (error) {
401
console.error('Invalid header value:', error.message);
402
// Error: Invalid character in header content ["Custom-Header"]
403
}
404
```