or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

caching.mdconnection-management.mdcookies.mdcore-http.mderrors.mdglobal-config.mdheaders-body.mdindex.mdinterceptors.mdmock-testing.mdweb-standards.md

headers-body.mddocs/

0

# Headers and Body Processing

1

2

HTTP headers management and request/response body handling with multiple content types and streaming support.

3

4

## Capabilities

5

6

### Headers

7

8

WHATWG Headers API implementation for managing HTTP headers with case-insensitive access and validation.

9

10

```javascript { .api }

11

/**

12

* HTTP headers management

13

*/

14

class Headers {

15

constructor(init?: HeadersInit);

16

17

append(name: string, value: string): void;

18

delete(name: string): void;

19

get(name: string): string | null;

20

getSetCookie(): string[];

21

has(name: string): boolean;

22

set(name: string, value: string): void;

23

24

keys(): IterableIterator<string>;

25

values(): IterableIterator<string>;

26

entries(): IterableIterator<[string, string]>;

27

forEach(callback: (value: string, key: string, parent: Headers) => void, thisArg?: any): void;

28

29

[Symbol.iterator](): IterableIterator<[string, string]>;

30

}

31

32

type HeadersInit =

33

| Headers

34

| Record<string, string | ReadonlyArray<string>>

35

| Iterable<readonly [string, string]>;

36

```

37

38

**Usage Examples:**

39

40

```javascript

41

import { Headers } from 'undici';

42

43

// Create headers from object

44

const headers = new Headers({

45

'Content-Type': 'application/json',

46

'Authorization': 'Bearer token123'

47

});

48

49

// Create headers from array

50

const headersFromArray = new Headers([

51

['content-type', 'text/html'],

52

['cache-control', 'no-cache']

53

]);

54

55

// Manipulate headers

56

headers.append('accept', 'application/json');

57

headers.set('user-agent', 'my-app/1.0');

58

headers.delete('authorization');

59

60

// Access headers (case-insensitive)

61

console.log(headers.get('content-type')); // 'application/json'

62

console.log(headers.has('Content-Type')); // true

63

64

// Iterate headers

65

for (const [name, value] of headers) {

66

console.log(`${name}: ${value}`);

67

}

68

69

headers.forEach((value, name) => {

70

console.log(`${name}: ${value}`);

71

});

72

73

// Handle Set-Cookie headers specially

74

const responseHeaders = new Headers();

75

responseHeaders.append('set-cookie', 'session=abc123; Path=/');

76

responseHeaders.append('set-cookie', 'theme=dark; Path=/');

77

78

const setCookies = responseHeaders.getSetCookie();

79

console.log(setCookies); // ['session=abc123; Path=/', 'theme=dark; Path=/']

80

```

81

82

### FormData

83

84

WHATWG FormData API implementation for handling multipart/form-data and form submissions.

85

86

```javascript { .api }

87

/**

88

* Form data handling for multipart/form-data

89

*/

90

class FormData {

91

constructor();

92

93

append(name: string, value: string | Blob, filename?: string): void;

94

delete(name: string): void;

95

get(name: string): FormDataEntryValue | null;

96

getAll(name: string): FormDataEntryValue[];

97

has(name: string): boolean;

98

set(name: string, value: string | Blob, filename?: string): void;

99

100

keys(): IterableIterator<string>;

101

values(): IterableIterator<FormDataEntryValue>;

102

entries(): IterableIterator<[string, FormDataEntryValue]>;

103

forEach(callback: (value: FormDataEntryValue, key: string, parent: FormData) => void, thisArg?: any): void;

104

105

[Symbol.iterator](): IterableIterator<[string, FormDataEntryValue]>;

106

}

107

108

type FormDataEntryValue = string | File;

109

```

110

111

**Usage Examples:**

112

113

```javascript

114

import { FormData, fetch } from 'undici';

115

import { readFileSync } from 'fs';

116

117

// Create form data

118

const formData = new FormData();

119

120

// Add text fields

121

formData.append('name', 'Alice');

122

formData.append('email', 'alice@example.com');

123

formData.append('message', 'Hello world!');

124

125

// Add file data

126

const fileBuffer = readFileSync('./document.pdf');

127

const file = new Blob([fileBuffer], { type: 'application/pdf' });

128

formData.append('document', file, 'document.pdf');

129

130

// Submit form data

131

const response = await fetch('https://api.example.com/upload', {

132

method: 'POST',

133

body: formData

134

// Content-Type header is automatically set with boundary

135

});

136

137

// Process existing form data

138

const existingFormData = new FormData();

139

existingFormData.append('field1', 'value1');

140

existingFormData.append('field2', 'value2');

141

existingFormData.append('field1', 'another value'); // Multiple values

142

143

console.log(existingFormData.get('field1')); // 'value1' (first value)

144

console.log(existingFormData.getAll('field1')); // ['value1', 'another value']

145

146

// Iterate form data

147

for (const [name, value] of existingFormData) {

148

console.log(`${name}: ${value}`);

149

}

150

```

151

152

### Body Processing

153

154

Body handling utilities and types for request and response body processing.

155

156

```javascript { .api }

157

/**

158

* Body mixin for consuming request/response bodies

159

*/

160

interface BodyMixin {

161

readonly body: ReadableStream | null;

162

readonly bodyUsed: boolean;

163

164

arrayBuffer(): Promise<ArrayBuffer>;

165

blob(): Promise<Blob>;

166

bytes(): Promise<Uint8Array>;

167

json(): Promise<any>;

168

text(): Promise<string>;

169

}

170

171

type BodyInit =

172

| ArrayBuffer

173

| AsyncIterable<Uint8Array>

174

| Blob

175

| FormData

176

| Iterable<Uint8Array>

177

| NodeJS.ArrayBufferView

178

| URLSearchParams

179

| null

180

| string;

181

182

interface BodyReadable extends Readable {

183

arrayBuffer(): Promise<ArrayBuffer>;

184

blob(): Promise<Blob>;

185

bytes(): Promise<Uint8Array>;

186

json(): Promise<any>;

187

text(): Promise<string>;

188

}

189

```

190

191

**Usage Examples:**

192

193

```javascript

194

import { fetch, request } from 'undici';

195

196

// Process different response body types

197

const response = await fetch('https://api.example.com/data');

198

199

// JSON response

200

if (response.headers.get('content-type')?.includes('application/json')) {

201

const data = await response.json();

202

console.log(data);

203

}

204

205

// Text response

206

if (response.headers.get('content-type')?.includes('text/')) {

207

const text = await response.text();

208

console.log(text);

209

}

210

211

// Binary response

212

if (response.headers.get('content-type')?.includes('image/')) {

213

const blob = await response.blob();

214

const arrayBuffer = await response.arrayBuffer();

215

const bytes = await response.bytes();

216

}

217

218

// Streaming response body

219

const streamResponse = await fetch('https://api.example.com/large-data');

220

const reader = streamResponse.body.getReader();

221

222

while (true) {

223

const { done, value } = await reader.read();

224

if (done) break;

225

226

// Process chunk

227

console.log('Received chunk:', value.length, 'bytes');

228

}

229

230

// Using undici.request for body processing

231

const { body } = await request('https://api.example.com/data');

232

const jsonData = await body.json();

233

234

// Send different body types

235

await fetch('https://api.example.com/upload', {

236

method: 'POST',

237

headers: { 'content-type': 'application/json' },

238

body: JSON.stringify({ message: 'hello' })

239

});

240

241

await fetch('https://api.example.com/upload', {

242

method: 'POST',

243

headers: { 'content-type': 'application/octet-stream' },

244

body: new ArrayBuffer(1024)

245

});

246

247

await fetch('https://api.example.com/upload', {

248

method: 'POST',

249

body: new URLSearchParams({ key: 'value', name: 'test' })

250

});

251

```

252

253

### MIME Type Processing

254

255

MIME type parsing and serialization utilities for content type handling.

256

257

```javascript { .api }

258

/**

259

* Parse MIME type strings according to WHATWG spec

260

* @param input - MIME type string to parse

261

* @returns Parsed MIME type object or failure

262

*/

263

function parseMIMEType(input: string): MimeType | 'failure';

264

265

/**

266

* Serialize MIME type object to string

267

* @param mimeType - MIME type object to serialize

268

* @returns Serialized MIME type string

269

*/

270

function serializeAMimeType(mimeType: MimeType): string;

271

272

interface MimeType {

273

type: string;

274

subtype: string;

275

parameters: Map<string, string>;

276

essence: string;

277

}

278

```

279

280

**Usage Examples:**

281

282

```javascript

283

import { parseMIMEType, serializeAMimeType } from 'undici';

284

285

// Parse MIME types

286

const mimeType = parseMIMEType('text/html; charset=utf-8');

287

if (mimeType !== 'failure') {

288

console.log(mimeType.type); // 'text'

289

console.log(mimeType.subtype); // 'html'

290

console.log(mimeType.essence); // 'text/html'

291

console.log(mimeType.parameters.get('charset')); // 'utf-8'

292

}

293

294

// Parse complex MIME type

295

const complexType = parseMIMEType('application/json; charset=utf-8; boundary=something');

296

if (complexType !== 'failure') {

297

console.log(complexType.parameters.get('boundary')); // 'something'

298

}

299

300

// Serialize MIME type

301

const serialized = serializeAMimeType({

302

type: 'application',

303

subtype: 'json',

304

parameters: new Map([['charset', 'utf-8']]),

305

essence: 'application/json'

306

});

307

console.log(serialized); // 'application/json; charset=utf-8'

308

309

// Handle parsing failures

310

const invalid = parseMIMEType('invalid-mime-type');

311

if (invalid === 'failure') {

312

console.log('Failed to parse MIME type');

313

}

314

```

315

316

### Header Utilities

317

318

Low-level header parsing utilities for advanced use cases.

319

320

```javascript { .api }

321

/**

322

* Parse raw headers into structured format

323

* @param headers - Raw headers to parse

324

* @returns Parsed headers object

325

*/

326

function parseHeaders(headers: Buffer | string): Record<string, string | string[]>;

327

328

/**

329

* Convert header names to canonical string format

330

* @param headerName - Header name to convert

331

* @returns Canonical header name string

332

*/

333

function headerNameToString(headerName: string | Buffer): string;

334

```

335

336

**Usage Examples:**

337

338

```javascript

339

import { parseHeaders, headerNameToString } from 'undici';

340

341

// Parse raw headers

342

const rawHeaders = Buffer.from(

343

'Content-Type: application/json\r\n' +

344

'Authorization: Bearer token123\r\n' +

345

'Set-Cookie: session=abc\r\n' +

346

'Set-Cookie: theme=dark\r\n'

347

);

348

349

const parsed = parseHeaders(rawHeaders);

350

console.log(parsed);

351

// {

352

// 'content-type': 'application/json',

353

// 'authorization': 'Bearer token123',

354

// 'set-cookie': ['session=abc', 'theme=dark']

355

// }

356

357

// Convert header names

358

console.log(headerNameToString('content-type')); // 'content-type'

359

console.log(headerNameToString(Buffer.from('AUTHORIZATION'))); // 'authorization'

360

```

361

362

### MIME Type Processing

363

364

Utilities for parsing and serializing MIME types according to RFC specifications.

365

366

```javascript { .api }

367

/**

368

* Parse a MIME type string into structured components

369

* @param input - MIME type string to parse

370

* @returns Parsed MIME type object or null if invalid

371

*/

372

function parseMIMEType(input: string): MIMEType | null;

373

374

/**

375

* Serialize a MIME type object back into a string

376

* @param mimeType - MIME type object to serialize

377

* @returns Serialized MIME type string

378

*/

379

function serializeAMimeType(mimeType: MIMEType): string;

380

381

interface MIMEType {

382

type: string;

383

subtype: string;

384

parameters: Map<string, string>;

385

}

386

```

387

388

**Usage Examples:**

389

390

```javascript

391

import { parseMIMEType, serializeAMimeType } from 'undici';

392

393

// Parse MIME type

394

const mimeType = parseMIMEType('text/html; charset=utf-8; boundary=something');

395

console.log(mimeType);

396

// {

397

// type: 'text',

398

// subtype: 'html',

399

// parameters: Map {

400

// 'charset' => 'utf-8',

401

// 'boundary' => 'something'

402

// }

403

// }

404

405

// Create MIME type object

406

const customMime = {

407

type: 'application',

408

subtype: 'json',

409

parameters: new Map([['charset', 'utf-8']])

410

};

411

412

// Serialize to string

413

const serialized = serializeAMimeType(customMime);

414

console.log(serialized); // 'application/json; charset=utf-8'

415

416

// Handle invalid MIME types

417

const invalid = parseMIMEType('not-a-valid-mime-type');

418

console.log(invalid); // null

419

```

420

421

## Types

422

423

### Content Types

424

425

```javascript { .api }

426

interface File extends Blob {

427

readonly name: string;

428

readonly lastModified: number;

429

}

430

431

interface Blob {

432

readonly size: number;

433

readonly type: string;

434

arrayBuffer(): Promise<ArrayBuffer>;

435

bytes(): Promise<Uint8Array>;

436

slice(start?: number, end?: number, contentType?: string): Blob;

437

stream(): ReadableStream<Uint8Array>;

438

text(): Promise<string>;

439

}

440

```

441

442

### Header Types

443

444

```javascript { .api }

445

type IncomingHttpHeaders = Record<string, string | string[]>;

446

type OutgoingHttpHeaders = Record<string, string | string[] | number>;

447

```