or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

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

tessl/npm-undici

An HTTP/1.1 client, written from scratch for Node.js

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/undici@7.15.x

To install, run

npx @tessl/cli install tessl/npm-undici@7.15.0

index.mddocs/

Undici

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.

Package Information

  • Package Name: undici
  • Package Type: npm
  • Language: JavaScript/TypeScript
  • Installation: npm install undici

Core Imports

import { 
  request, 
  stream, 
  fetch, 
  Agent, 
  Client, 
  Pool,
  WebSocket,
  EventSource,
  Headers,
  Response,
  Request,
  FormData,
  buildConnector,
  util,
  parseMIMEType,
  serializeAMimeType,
  ping
} from 'undici';

For CommonJS:

const { 
  request, 
  stream, 
  fetch, 
  Agent, 
  Client, 
  Pool,
  WebSocket,
  EventSource,
  Headers,
  Response,
  Request,
  FormData,
  buildConnector,
  util,
  parseMIMEType,
  serializeAMimeType,
  ping
} = require('undici');

Basic Usage

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

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

// WHATWG fetch API (standards compliant)
const response = await fetch('https://api.example.com/data');
const data = await response.json();

// Advanced configuration with custom agent
const agent = new Agent({ 
  keepAliveTimeout: 10000,
  keepAliveMaxTimeout: 60000 
});
setGlobalDispatcher(agent);

Architecture

Undici is built around several key architectural patterns:

  • Dispatcher Pattern: All HTTP clients inherit from base Dispatcher class providing consistent APIs
  • Connection Management: Hierarchical system from Client (single connection) to Pool (origin-based) to Agent (multi-origin)
  • Web Standards Compliance: Full WHATWG fetch, WebSocket, EventSource, and related API implementations
  • Interceptor System: Composable middleware for request/response processing
  • Mock Framework: Comprehensive testing utilities with call history tracking
  • Streaming Architecture: Native support for Node.js streams and Web Streams

Capabilities

Core HTTP Client APIs

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

function request(url: string | URL, options?: RequestOptions): Promise<ResponseData>;
function stream(url: string | URL, options: RequestOptions, factory: StreamFactory): Promise<StreamData>;
function pipeline(url: string | URL, options: PipelineOptions, handler: PipelineHandler): Duplex;
function connect(url: string | URL, options?: ConnectOptions): Promise<ConnectData>;
function upgrade(url: string | URL, options?: UpgradeOptions): Promise<UpgradeData>;

Core HTTP APIs

Connection Management

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

class Client extends Dispatcher {
  constructor(url: string | URL, options?: Client.Options);
}

class Pool extends Dispatcher {
  constructor(url: string | URL, options?: Pool.Options);
}

class Agent extends Dispatcher {
  constructor(options?: Agent.Options);
}

Connection Management

Web Standards Implementation

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

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

class WebSocket extends EventTarget {
  constructor(url: string | URL, protocols?: string | string[]);
  send(data: string | ArrayBuffer | ArrayBufferView | Blob): void;
  close(code?: number, reason?: string): void;
}

class EventSource extends EventTarget {
  constructor(url: string | URL, eventSourceInitDict?: EventSourceInit);
}

Web Standards

Headers and Body Processing

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

class Headers {
  constructor(init?: HeadersInit);
  append(name: string, value: string): void;
  delete(name: string): void;
  get(name: string): string | null;
  has(name: string): boolean;
  set(name: string, value: string): void;
}

class FormData {
  constructor();
  append(name: string, value: string | Blob, filename?: string): void;
  delete(name: string): void;
  get(name: string): FormDataEntryValue | null;
  has(name: string): boolean;
  set(name: string, value: string | Blob, filename?: string): void;
}

Headers and Body

Cookie Management

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

function getCookies(headers: IncomingHttpHeaders): Record<string, string>;
function getSetCookies(headers: IncomingHttpHeaders): string[];
function setCookie(headers: OutgoingHttpHeaders, cookie: Cookie): void;
function deleteCookie(headers: OutgoingHttpHeaders, name: string, attributes?: CookieAttributes): void;
function parseCookie(cookie: string): Cookie;

Cookie Management

Interceptors and Middleware

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

const interceptors: {
  redirect(options?: RedirectInterceptorOpts): DispatcherComposeInterceptor;
  retry(options?: RetryInterceptorOpts): DispatcherComposeInterceptor;
  cache(options?: CacheInterceptorOpts): DispatcherComposeInterceptor;
  decompress(options?: DecompressInterceptorOpts): DispatcherComposeInterceptor;
  dump(options?: DumpInterceptorOpts): DispatcherComposeInterceptor;
  dns(options?: DnsInterceptorOpts): DispatcherComposeInterceptor;
  responseError(options?: ResponseErrorInterceptorOpts): DispatcherComposeInterceptor;
};

Interceptors

Caching System

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

const caches: CacheStorage;

const cacheStores: {
  MemoryCacheStore: typeof MemoryCacheStore;
  SqliteCacheStore: typeof SqliteCacheStore;
};

Caching

Mock Testing Framework

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

class MockAgent extends Dispatcher {
  constructor(options?: MockAgent.Options);
  get(origin: string | RegExp | URL): MockPool;
  close(): Promise<void>;
}

class MockPool extends Dispatcher {
  intercept(options: MockInterceptor.Options): MockInterceptor;
}

Mock Testing

Error Handling

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

const errors: {
  UndiciError: typeof UndiciError;
  ConnectTimeoutError: typeof ConnectTimeoutError;
  HeadersTimeoutError: typeof HeadersTimeoutError;
  BodyTimeoutError: typeof BodyTimeoutError;
  ResponseError: typeof ResponseError;
  InvalidArgumentError: typeof InvalidArgumentError;
  // ... additional error types
};

Error Handling

Utility Functions

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

const util: {
  parseHeaders(headers: string): IncomingHttpHeaders;
  headerNameToString(headerName: string | Buffer): string;
};

function parseMIMEType(input: string): MIMEType | null;
function serializeAMimeType(mimeType: MIMEType): string;
function buildConnector(options?: ConnectorOptions): Connector;
function ping(ws: WebSocket, data?: Buffer): void;

Global Configuration

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

function setGlobalDispatcher(dispatcher: Dispatcher): void;
function getGlobalDispatcher(): Dispatcher;
function setGlobalOrigin(origin: string | URL): void;
function getGlobalOrigin(): string | undefined;
function install(): void;

Global Configuration

Types

Core Types

interface RequestOptions {
  method?: string;
  headers?: IncomingHttpHeaders;
  body?: BodyInit;
  query?: Record<string, any>;
  idempotent?: boolean;
  blocking?: boolean;
  upgrade?: boolean;
  headersTimeout?: number;
  bodyTimeout?: number;
  reset?: boolean;
  throwOnError?: boolean;
  expectContinue?: boolean;
}

interface ResponseData {
  statusCode: number;
  headers: IncomingHttpHeaders;
  body: BodyReadable;
  trailers: Record<string, string>;
  opaque: unknown;
  context: {
    history: readonly URL[];
  };
}

type BodyInit = 
  | ArrayBuffer 
  | AsyncIterable<Uint8Array> 
  | Blob 
  | FormData 
  | Iterable<Uint8Array> 
  | NodeJS.ArrayBufferView 
  | URLSearchParams 
  | null 
  | string;