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

index.mddocs/

0

# Undici

1

2

Undici is a high-performance HTTP/1.1 client written from scratch for Node.js, providing comprehensive HTTP request capabilities including fetch API compatibility, streaming, pipelining, and advanced connection management. It delivers superior performance through efficient connection pooling, HTTP/1.1 pipelining support, and comprehensive Web Standards compliance.

3

4

## Package Information

5

6

- **Package Name**: undici

7

- **Package Type**: npm

8

- **Language**: JavaScript/TypeScript

9

- **Installation**: `npm install undici`

10

11

## Core Imports

12

13

```javascript

14

import {

15

request,

16

stream,

17

fetch,

18

Agent,

19

Client,

20

Pool,

21

WebSocket,

22

EventSource,

23

Headers,

24

Response,

25

Request,

26

FormData,

27

buildConnector,

28

util,

29

parseMIMEType,

30

serializeAMimeType,

31

ping

32

} from 'undici';

33

```

34

35

For CommonJS:

36

37

```javascript

38

const {

39

request,

40

stream,

41

fetch,

42

Agent,

43

Client,

44

Pool,

45

WebSocket,

46

EventSource,

47

Headers,

48

Response,

49

Request,

50

FormData,

51

buildConnector,

52

util,

53

parseMIMEType,

54

serializeAMimeType,

55

ping

56

} = require('undici');

57

```

58

59

## Basic Usage

60

61

```javascript

62

import { request, fetch, Agent, setGlobalDispatcher } from 'undici';

63

64

// High-performance request API

65

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

66

const data = await body.json();

67

68

// WHATWG fetch API (standards compliant)

69

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

70

const data = await response.json();

71

72

// Advanced configuration with custom agent

73

const agent = new Agent({

74

keepAliveTimeout: 10000,

75

keepAliveMaxTimeout: 60000

76

});

77

setGlobalDispatcher(agent);

78

```

79

80

## Architecture

81

82

Undici is built around several key architectural patterns:

83

84

- **Dispatcher Pattern**: All HTTP clients inherit from base Dispatcher class providing consistent APIs

85

- **Connection Management**: Hierarchical system from Client (single connection) to Pool (origin-based) to Agent (multi-origin)

86

- **Web Standards Compliance**: Full WHATWG fetch, WebSocket, EventSource, and related API implementations

87

- **Interceptor System**: Composable middleware for request/response processing

88

- **Mock Framework**: Comprehensive testing utilities with call history tracking

89

- **Streaming Architecture**: Native support for Node.js streams and Web Streams

90

91

## Capabilities

92

93

### Core HTTP Client APIs

94

95

High-performance HTTP request methods optimized for different use cases, from simple requests to complex streaming scenarios.

96

97

```javascript { .api }

98

function request(url: string | URL, options?: RequestOptions): Promise<ResponseData>;

99

function stream(url: string | URL, options: RequestOptions, factory: StreamFactory): Promise<StreamData>;

100

function pipeline(url: string | URL, options: PipelineOptions, handler: PipelineHandler): Duplex;

101

function connect(url: string | URL, options?: ConnectOptions): Promise<ConnectData>;

102

function upgrade(url: string | URL, options?: UpgradeOptions): Promise<UpgradeData>;

103

```

104

105

[Core HTTP APIs](./core-http.md)

106

107

### Connection Management

108

109

Dispatcher classes for managing HTTP connections at different scales, from single connections to multi-origin load balancing.

110

111

```javascript { .api }

112

class Client extends Dispatcher {

113

constructor(url: string | URL, options?: Client.Options);

114

}

115

116

class Pool extends Dispatcher {

117

constructor(url: string | URL, options?: Pool.Options);

118

}

119

120

class Agent extends Dispatcher {

121

constructor(options?: Agent.Options);

122

}

123

```

124

125

[Connection Management](./connection-management.md)

126

127

### Web Standards Implementation

128

129

Complete WHATWG-compliant implementations of fetch, WebSocket, EventSource, and related Web APIs.

130

131

```javascript { .api }

132

function fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;

133

134

class WebSocket extends EventTarget {

135

constructor(url: string | URL, protocols?: string | string[]);

136

send(data: string | ArrayBuffer | ArrayBufferView | Blob): void;

137

close(code?: number, reason?: string): void;

138

}

139

140

class EventSource extends EventTarget {

141

constructor(url: string | URL, eventSourceInitDict?: EventSourceInit);

142

}

143

```

144

145

[Web Standards](./web-standards.md)

146

147

### Headers and Body Processing

148

149

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

150

151

```javascript { .api }

152

class Headers {

153

constructor(init?: HeadersInit);

154

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

155

delete(name: string): void;

156

get(name: string): string | null;

157

has(name: string): boolean;

158

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

159

}

160

161

class FormData {

162

constructor();

163

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

164

delete(name: string): void;

165

get(name: string): FormDataEntryValue | null;

166

has(name: string): boolean;

167

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

168

}

169

```

170

171

[Headers and Body](./headers-body.md)

172

173

### Cookie Management

174

175

Complete cookie handling utilities for both client and server-side cookie operations.

176

177

```javascript { .api }

178

function getCookies(headers: IncomingHttpHeaders): Record<string, string>;

179

function getSetCookies(headers: IncomingHttpHeaders): string[];

180

function setCookie(headers: OutgoingHttpHeaders, cookie: Cookie): void;

181

function deleteCookie(headers: OutgoingHttpHeaders, name: string, attributes?: CookieAttributes): void;

182

function parseCookie(cookie: string): Cookie;

183

```

184

185

[Cookie Management](./cookies.md)

186

187

### Interceptors and Middleware

188

189

Composable interceptor system for request/response processing with built-in interceptors for common needs.

190

191

```javascript { .api }

192

const interceptors: {

193

redirect(options?: RedirectInterceptorOpts): DispatcherComposeInterceptor;

194

retry(options?: RetryInterceptorOpts): DispatcherComposeInterceptor;

195

cache(options?: CacheInterceptorOpts): DispatcherComposeInterceptor;

196

decompress(options?: DecompressInterceptorOpts): DispatcherComposeInterceptor;

197

dump(options?: DumpInterceptorOpts): DispatcherComposeInterceptor;

198

dns(options?: DnsInterceptorOpts): DispatcherComposeInterceptor;

199

responseError(options?: ResponseErrorInterceptorOpts): DispatcherComposeInterceptor;

200

};

201

```

202

203

[Interceptors](./interceptors.md)

204

205

### Caching System

206

207

HTTP caching implementation with multiple storage backends and standards-compliant cache behavior.

208

209

```javascript { .api }

210

const caches: CacheStorage;

211

212

const cacheStores: {

213

MemoryCacheStore: typeof MemoryCacheStore;

214

SqliteCacheStore: typeof SqliteCacheStore;

215

};

216

```

217

218

[Caching](./caching.md)

219

220

### Mock Testing Framework

221

222

Comprehensive testing utilities for mocking HTTP requests, recording interactions, and testing HTTP clients.

223

224

```javascript { .api }

225

class MockAgent extends Dispatcher {

226

constructor(options?: MockAgent.Options);

227

get(origin: string | RegExp | URL): MockPool;

228

close(): Promise<void>;

229

}

230

231

class MockPool extends Dispatcher {

232

intercept(options: MockInterceptor.Options): MockInterceptor;

233

}

234

```

235

236

[Mock Testing](./mock-testing.md)

237

238

### Error Handling

239

240

Comprehensive error classes for different types of HTTP client failures with detailed error information.

241

242

```javascript { .api }

243

const errors: {

244

UndiciError: typeof UndiciError;

245

ConnectTimeoutError: typeof ConnectTimeoutError;

246

HeadersTimeoutError: typeof HeadersTimeoutError;

247

BodyTimeoutError: typeof BodyTimeoutError;

248

ResponseError: typeof ResponseError;

249

InvalidArgumentError: typeof InvalidArgumentError;

250

// ... additional error types

251

};

252

```

253

254

[Error Handling](./errors.md)

255

256

### Utility Functions

257

258

Helper utilities for HTTP header parsing, MIME type processing, and connection building.

259

260

```javascript { .api }

261

const util: {

262

parseHeaders(headers: string): IncomingHttpHeaders;

263

headerNameToString(headerName: string | Buffer): string;

264

};

265

266

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

267

function serializeAMimeType(mimeType: MIMEType): string;

268

function buildConnector(options?: ConnectorOptions): Connector;

269

function ping(ws: WebSocket, data?: Buffer): void;

270

```

271

272

### Global Configuration

273

274

Global settings for default dispatchers, origins, and Web API installation.

275

276

```javascript { .api }

277

function setGlobalDispatcher(dispatcher: Dispatcher): void;

278

function getGlobalDispatcher(): Dispatcher;

279

function setGlobalOrigin(origin: string | URL): void;

280

function getGlobalOrigin(): string | undefined;

281

function install(): void;

282

```

283

284

[Global Configuration](./global-config.md)

285

286

## Types

287

288

### Core Types

289

290

```javascript { .api }

291

interface RequestOptions {

292

method?: string;

293

headers?: IncomingHttpHeaders;

294

body?: BodyInit;

295

query?: Record<string, any>;

296

idempotent?: boolean;

297

blocking?: boolean;

298

upgrade?: boolean;

299

headersTimeout?: number;

300

bodyTimeout?: number;

301

reset?: boolean;

302

throwOnError?: boolean;

303

expectContinue?: boolean;

304

}

305

306

interface ResponseData {

307

statusCode: number;

308

headers: IncomingHttpHeaders;

309

body: BodyReadable;

310

trailers: Record<string, string>;

311

opaque: unknown;

312

context: {

313

history: readonly URL[];

314

};

315

}

316

317

type BodyInit =

318

| ArrayBuffer

319

| AsyncIterable<Uint8Array>

320

| Blob

321

| FormData

322

| Iterable<Uint8Array>

323

| NodeJS.ArrayBufferView

324

| URLSearchParams

325

| null

326

| string;

327

```