Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
U

undici

> 开发工具
Open source

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

7.7K stars0 likes1 views
WebsiteGitHub

About

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

undici

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

Undici means eleven in Italian. 1.1 -> 11 -> Eleven -> Undici. It is also a Stranger Things reference.

How to get involved

Have a question about using Undici? Open a Q&A Discussion or join our official OpenJS Slack channel.

Looking to contribute? Start by reading the contributing guide

Install

bash
npm i undici

Benchmarks

The benchmark is a simple getting data example using 50 TCP connections with a pipelining depth of 10 running on Node 24.14.1.

HTTP/1.1

…

HTTP/1.1 over HTTPS

Using benchmark-https.js against an h1-over-TLS server (50 connections, pipelining depth 10, Node 24.14.1).

…

HTTP/2

Using benchmark-http2.js against an h2 server (50 connections, pipelining depth 10, Node 24.14.1).

…

Undici vs. Fetch

Overview

Node.js includes a built-in fetch() implementation powered by undici starting from Node.js v18. However, there are important differences between using the built-in fetch and installing undici as a separate module.

Built-in Fetch (Node.js v18+)

Node.js's built-in fetch is powered by a bundled version of undici:

javascript
// Available globally in Node.js v18+
const response = await fetch('https://api.example.com/data');
const data = await response.json();

// Check the bundled undici version
console.log(process.versions.undici); // e.g., "5.28.4"

Pros:

  • No additional dependencies required
  • Works across different JavaScript runtimes
  • Automatic compression handling (gzip, deflate, br)
  • Built-in caching support (in development)

Cons:

  • Limited to the undici version bundled with your Node.js version
  • Less control over connection pooling and advanced features
  • Error handling follows Web API standards (errors wrapped in TypeError)
  • Performance overhead due to Web Streams implementation

Undici Module

Installing undici as a separate module gives you access to the latest features and APIs:

bash
npm install undici
javascript
import { request, fetch, Agent, setGlobalDispatcher } from 'undici';

// Use undici.request for maximum performance
const { statusCode, headers, body } = await request('https://api.example.com/data');
const data = await body.json();

// Or use undici.fetch with custom configuration
const agent = new Agent({ keepAliveTimeout: 10000 });
setGlobalDispatcher(agent);
const response = await fetch('https://api.example.com/data');

Pros:

  • Latest undici features and bug fixes
  • Access to advanced APIs (request, stream, pipeline)
  • Fine-grained control over connection pooling
  • Better error handling with clearer error messages
  • Superior performance, especially with undici.request
  • HTTP/1.1 pipelining support
  • Custom interceptors and middleware
  • Advanced features like ProxyAgent, Socks5Agent, MockAgent

Cons:

  • Additional dependency to manage
  • Larger bundle size

When to Use Each

Use Built-in Fetch When:

  • You want zero dependencies
  • Building isomorphic code that runs in browsers and Node.js
  • Publishing to npm and want to maximize compatibility with JS runtimes
  • Simple HTTP requests without advanced configuration
  • You're publishing to npm and you want to maximize compatiblity
  • You don't depend on features from a specific version of undici

Use Undici Module When:

  • You need the latest undici features and performance improvements
  • You require advanced connection pooling configuration
  • You need APIs not available in the built-in fetch (ProxyAgent, Socks5Agent, MockAgent, etc.)
  • Performance is critical (use undici.request for maximum speed)
  • You want better error handling and debugging capabilities
  • You need HTTP/1.1 pipelining or advanced interceptors
  • You prefer decoupled protocol and API interfaces

Performance Comparison

Based on benchmarks, here's the typical performance hierarchy:

  1. undici.request() - Fastest, most efficient
  2. undici.fetch() - Good performance, standard compliance
  3. Node.js http/https - Baseline performance

Migration Guide

If you're currently using built-in fetch and want to migrate to undici:

javascript
// Before: Built-in fetch
const response = await fetch('https://api.example.com/data');

// After: Undici fetch (drop-in replacement)
import { fetch } from 'undici';
const response = await fetch('https://api.example.com/data');

// Or: Undici request (better performance)
import { request } from 'undici';
const { statusCode, body } = await request('https://api.example.com/data');
const data = await body.json();

Keep fetch and FormData together

When you send a FormData body, keep fetch and FormData from the same implementation.

Use one of these patterns:

javascript
// Built-in globals
const body = new FormData()
body.set('name', 'some')
await fetch('https://example.com', {
  method: 'POST',
  body
})
javascript
// undici module imports
import { fetch, FormData } from 'undici'

const body = new FormData()
body.set('name', 'some')
await fetch('https://example.com', {
  method: 'POST',
  body
})

If you want the installed undici package to provide the globals, call install() first:

javascript
import { install } from 'undici'

install()

const body = new FormData()
body.set('name', 'some')
await fetch('https://example.com', {
  method: 'POST',
  body
})

install() replaces the global fetch, Headers, Response, Request, and FormData implementations with undici's versions, so they all match. It also installs undici's WebSocket, CloseEvent, ErrorEvent, MessageEvent, and EventSource globals.

Avoid mixing a global FormData with undici.fetch(), or undici.FormData with the built-in global fetch().

Version Compatibility

You can check which version of undici is bundled with your Node.js version:

javascript
console.log(process.versions.undici);

Installing undici as a module allows you to use a newer version than what's bundled with Node.js, giving you access to the latest features and performance improvements.

Quick Start

Basic Request

javascript
import { request } from 'undici'

const {
  statusCode,
  headers,
  trailers,
  body
} = await request('http://localhost:3000/foo')

console.log('response received', statusCode)
console.log('headers', headers)

for await (const data of body) { console.log('data', data) }

console.log('trailers', trailers)

Using Cache Interceptor

Undici provides a powerful HTTP caching interceptor that follows HTTP caching best practices. Here's how to use it:

…

Key Features:

  • Automatic Caching: Respects Cache-Control and Expires headers
  • Validation: Supports ETag and Last-Modified validation
  • Storage Options: In-memory or persistent SQLite storage
  • Flexible: Configure cache size, TTL, and more

Global Installation

Undici provides an install() function to add fetch-related and other web API classes to globalThis, making them available globally:

javascript
import { install } from 'undici'

// Install undici's global web APIs
install()

// Now you can use fetch classes globally without importing
const response = await fetch('https://api.example.com/data')
const data = await response.json()

// All classes are available globally:
const headers = new Headers([['content-type', 'application/json']])
const request = new Request('https://example.com')
const formData = new FormData()
const ws = new WebSocket('wss://example.com')
const eventSource = new EventSource('https://example.com/events')

The install() function adds the following classes to globalThis:

  • fetch - The fetch function
  • Headers - HTTP headers management
  • Response - HTTP response representation
  • Request - HTTP request representation
  • FormData - Form data handling
  • WebSocket - WebSocket client
  • CloseEvent, ErrorEvent, MessageEvent - WebSocket events
  • EventSource - Server-sent events client

When you call install(), these globals come from the same undici implementation. For example, global fetch and global FormData will both be undici's versions, and WebSocket and EventSource will also come from undici, which is the recommended setup if you want to use undici through globals.

This is useful for:

  • Polyfilling environments that don't have fetch
  • Ensuring consistent fetch behavior across different Node.js versions
  • Making undici's implementations available globally for libraries that expect them

Body Mixins

The body mixins are the most common way to format the request/response body. Mixins include:

  • .arrayBuffer()
  • .blob()
  • .bytes()
  • .json()
  • .text()

[!NOTE] The body returned from undici.request does not implement .formData().

[!WARNING] Calling body.formData() on a fetch response causes undici to buffer and parse the entire body. Since this is dictated by the spec, body.formData() must only be called on responses from trusted servers.

Example usage:

javascript
import { request } from 'undici'

const {
  statusCode,
  headers,
  trailers,
  body
} = await request('http://localhost:3000/foo')

console.log('response received', statusCode)
console.log('headers', headers)
console.log('data', await body.json())
console.log('trailers', trailers)

Note: Once a mixin has been called then the body cannot be reused, thus calling additional mixins on .body, e.g. .body.json(); .body.text() will result in an error TypeError: unusable being thrown and returned through the Promise rejection.

Should you need to access the body in plain-text after using a mixin, the best practice is to use the .text() mixin first and then manually parse the text to the desired format.

For more information about their behavior, please reference the body mixin from the Fetch Standard.

Common API Methods

This section documents our most commonly used API methods. Additional APIs are documented in their own files within the docs folder and are accessible via the navigation list on the left side of the docs site.

For the top-level APIs below, the url argument supplies the request origin and path. Do not pass origin or path in the second options argument. The linked Dispatcher option types include those fields because dispatcher methods are lower-level APIs that do not receive a separate url argument.

undici.request([url, options]): Promise

Arguments:

  • url string | URL | UrlObject
  • options RequestOptions
    • dispatcher Dispatcher - Default: getGlobalDispatcher
    • method String - Default: PUT if options.body, otherwise GET

Returns a promise with the result of the Dispatcher.request method.

Calls options.dispatcher.request(options).

See Dispatcher.request for more details, and request examples for examples.

undici.stream([url, options, ]factory): Promise

Arguments:

  • url string | URL | UrlObject
  • options StreamOptions
    • dispatcher Dispatcher - Default: [getG

Issues· 368 open

View all issuesOpen on GitHub
  • #5936

    HTTP/2 idle reaper crashes the process: InformationalError: socket idle timeout is emitted on a ClientHttp2Stream with no 'error' listener

    bugUpdated Oct 1, 2026
  • #5938

    build: build milo through the same WASM build infrastructure as llhttp

    Updated Oct 1, 2026
  • #5928

    Fix `test:typescript` script for Windows compatibility

    bugUpdated Sep 30, 2026
  • #2019

    SSRF protection in undici / native-node-fetch

    enhancementgood first issueUpdated Sep 28, 2026
  • #5500

    Importing undici v8 silently breaks Node's bundled fetch via the legacy globalDispatcher bridge (v8's stricter core Request rejects opts the bundled v6 core accepts — e.g. request-set Content-Length)

    Updated Sep 28, 2026
  • #5900

    HTTP/1.1 304 with Content-Length closes the connection

    bugUpdated Sep 28, 2026
  • #2675

    HTTP2 Requests hang upon receiving 'Stream closed with error code NGHTTP2_INTERNAL_ERROR'

    buggood first issueH2Updated Sep 28, 2026
  • #5919

    undici-types 6.21.x: a trusted-publisher re-release would unblock current `@types/node@20/22` under pnpm `trustPolicy`

    Updated Sep 27, 2026
  • #5835

    `FormData` body with an errored `Blob` part crashes the process with an unhandled rejection instead of erroring the body stream (regression in 7.20.0)

    Updated Sep 27, 2026
  • #5912

    Should Fetch retry reusable request bodies after HTTP/2 GOAWAY?

    Updated Sep 27, 2026

> Tags

JavaScriptclienthttpnodejs

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedOct 1, 2026
Category开发工具
PricingOpen source

> Related tools

V
VS Code
流行的开源代码编辑器
G
Git
分布式版本控制系统
V
Vite
下一代前端构建工具