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
npm i undiciBenchmarks
The benchmark is a simple getting data example using a 50 TCP connections with a pipelining depth of 10 running on Node 22.11.0.
ββββββββββββββββββββββββββ¬ββββββββββ¬βββββββββββββββββββββ¬βββββββββββββ¬ββββββββββββββββββββββββββ
β Tests β Samples β Result β Tolerance β Difference with slowest β
ββββββββββββββββββββββββββΌββββββββββΌβββββββββββββββββββββΌβββββββββββββΌββββββββββββββββββββββββββ€
β 'axios' β 15 β '5708.26 req/sec' β 'Β± 2.91 %' β '-' β
β 'http - no keepalive' β 10 β '5809.80 req/sec' β 'Β± 2.30 %' β '+ 1.78 %' β
β 'request' β 30 β '5828.80 req/sec' β 'Β± 2.91 %' β '+ 2.11 %' β
β 'undici - fetch' β 40 β '5903.78 req/sec' β 'Β± 2.87 %' β '+ 3.43 %' β
β 'node-fetch' β 10 β '5945.40 req/sec' β 'Β± 2.13 %' β '+ 4.15 %' β
β 'got' β 35 β '6511.45 req/sec' β 'Β± 2.84 %' β '+ 14.07 %' β
β 'http - keepalive' β 65 β '9193.24 req/sec' β 'Β± 2.92 %' β '+ 61.05 %' β
β 'superagent' β 35 β '9339.43 req/sec' β 'Β± 2.95 %' β '+ 63.61 %' β
β 'undici - pipeline' β 50 β '13364.62 req/sec' β 'Β± 2.93 %' β '+ 134.13 %' β
β 'undici - stream' β 95 β '18245.36 req/sec' β 'Β± 2.99 %' β '+ 219.63 %' β
β 'undici - request' β 50 β '18340.17 req/sec' β 'Β± 2.84 %' β '+ 221.29 %' β
β 'undici - dispatch' β 40 β '22234.42 req/sec' β 'Β± 2.94 %' β '+ 289.51 %' β
ββββββββββββββββββββββββββ΄ββββββββββ΄βββββββββββββββββββββ΄βββββββββββββ΄ββββββββββββββββββββββββββ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:
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:
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.requestHTTP/1.1 pipelining support
Custom interceptors and middleware
Advanced features like
ProxyAgent,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
Simple HTTP requests without advanced configuration
You're okay with the undici version bundled in your Node.js version
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,MockAgent, etc.)Performance is critical (use
undici.requestfor 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:
undici.request()- Fastest, most efficientundici.fetch()- Good performance, standard complianceNode.js
http/https- Baseline performance
Migration Guide
If you're currently using built-in fetch and want to migrate to undici:
Version Compatibility
You can check which version of undici is bundled with your Node.js version:
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
Global Installation
Undici provides an install() function to add all WHATWG fetch classes to globalThis, making them available globally:
The install() function adds the following classes to globalThis:
fetch- The fetch functionHeaders- HTTP headers managementResponse- HTTP response representationRequest- HTTP request representationFormData- Form data handlingWebSocket- WebSocket clientCloseEvent,ErrorEvent,MessageEvent- WebSocket eventsEventSource- Server-sent events client
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:
[!NOTE] The body returned from
undici.requestdoes not implement.formData().
Example usage:
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.
undici.request([url, options]): Promise
undici.request([url, options]): PromiseArguments:
url
string | URL | UrlObjectoptions
RequestOptionsdispatcher
Dispatcher- Default: getGlobalDispatchermethod
String- Default:PUTifoptions.body, otherwiseGET
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
undici.stream([url, options, ]factory): PromiseArguments:
url
string | URL | UrlObjectoptions
StreamOptionsdispatcher
Dispatcher- Default: getGlobalDispatchermethod
String- Default:PUTifoptions.body, otherwiseGET
factory
Dispatcher.stream.factory
Returns a promise with the result of the Dispatcher.stream method.
Calls options.dispatcher.stream(options, factory).
See Dispatcher.stream for more details.
undici.pipeline([url, options, ]handler): Duplex
undici.pipeline([url, options, ]handler): DuplexArguments:
url
string | URL | UrlObjectoptions
PipelineOptionsdispatcher
Dispatcher- Default: getGlobalDispatchermethod
String- Default:PUTifoptions.body, otherwiseGET
handler
Dispatcher.pipeline.handler
Returns: stream.Duplex
Calls options.dispatch.pipeline(options, handler).
See Dispatcher.pipeline for more details.
undici.connect([url, options]): Promise
undici.connect([url, options]): PromiseStarts two-way communications with the requested resource using HTTP CONNECT.
Arguments:
url
string | URL | UrlObjectoptions
ConnectOptionsdispatcher
Dispatcher- Default: getGlobalDispatcher
callback
(err: Error | null, data: ConnectData | null) => void(optional)
Returns a promise with the result of the Dispatcher.connect method.
Calls options.dispatch.connect(options).
See Dispatcher.connect for more details.
undici.fetch(input[, init]): Promise
undici.fetch(input[, init]): PromiseImplements fetch.
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
https://fetch.spec.whatwg.org/#fetch-method
Basic usage example:
You can pass an optional dispatcher to fetch as:
request.body
request.bodyA body can be of the following types:
ArrayBuffer
ArrayBufferView
AsyncIterables
Blob
Iterables
String
URLSearchParams
FormData
In this implementation of fetch, request.body now accepts Async Iterables. It is not present in the Fetch Standard.
FormData besides text data and buffers can also utilize streams via Blob objects:
request.duplex
request.duplex'half'
In this implementation of fetch, request.duplex must be set if request.body is ReadableStream or Async Iterables, however, even though the value must be set to 'half', it is actually a full duplex. For more detail refer to the Fetch Standard.
response.body
response.bodyNodejs has two kinds of streams: web streams, which follow the API of the WHATWG web standard found in browsers, and an older Node-specific streams API. response.body returns a readable web stream. If you would prefer to work with a Node stream you can convert a web stream using .fromWeb().
Specification Compliance
This section documents parts of the HTTP/1.1 and Fetch Standard that Undici does not support or does not fully implement.
CORS
Unlike browsers, Undici does not implement CORS (Cross-Origin Resource Sharing) checks by default. This means:
No preflight requests are automatically sent for cross-origin requests
No validation of
Access-Control-Allow-Originheaders is performedRequests to any origin are allowed regardless of the source
This behavior is intentional for server-side environments where CORS restrictions are typically unnecessary. If your application requires CORS-like protections, you will need to implement these checks manually.
Garbage Collection
https://fetch.spec.whatwg.org/#garbage-collection
The Fetch Standard allows users to skip consuming the response body by relying on garbage collection to release connection resources. Undici does not do the same. Therefore, it is important to always either consume or cancel the response body.
Garbage collection in Node is less aggressive and deterministic (due to the lack of clear idle periods that browsers have through the rendering refresh rate) which means that leaving the release of connection resources to the garbage collector can lead to excessive connection usage, reduced performance (due to less connection re-use), and even stalls or deadlocks when running out of connections.
The same applies for request too:
However, if you want to get only headers, it might be better to use HEAD request method. Usage of this method will obviate the need for consumption or cancelling of the response body. See MDN - HTTP - HTTP request methods - HEAD for more details.
Forbidden and Safelisted Header Names
https://fetch.spec.whatwg.org/#cors-safelisted-response-header-name
https://fetch.spec.whatwg.org/#forbidden-header-name
https://fetch.spec.whatwg.org/#forbidden-response-header-name
https://github.com/wintercg/fetch/issues/6
The Fetch Standard requires implementations to exclude certain headers from requests and responses. In browser environments, some headers are forbidden so the user agent remains in full control over them. In Undici, these constraints are removed to give more control to the user.
undici.upgrade([url, options]): Promise
undici.upgrade([url, options]): PromiseUpgrade to a different protocol. See MDN - HTTP - Protocol upgrade mechanism for more details.
Arguments:
url
string | URL | UrlObjectoptions
UpgradeOptionsdispatcher
Dispatcher- Default: getGlobalDispatcher
callback
(error: Error | null, data: UpgradeData) => void(optional)
Returns a promise with the result of the Dispatcher.upgrade method.
Calls options.dispatcher.upgrade(options).
See Dispatcher.upgrade for more details.
undici.setGlobalDispatcher(dispatcher)
undici.setGlobalDispatcher(dispatcher)dispatcher
Dispatcher
Sets the global dispatcher used by Common API Methods. Global dispatcher is shared among compatible undici modules, including undici that is bundled internally with node.js.
undici.getGlobalDispatcher()
undici.getGlobalDispatcher()Gets the global dispatcher used by Common API Methods.
Returns: Dispatcher
undici.setGlobalOrigin(origin)
undici.setGlobalOrigin(origin)origin
string | URL | undefined
Sets the global origin used in fetch.
If undefined is passed, the global origin will be reset. This will cause Response.redirect, new Request(), and fetch to throw an error when a relative path is passed.
undici.getGlobalOrigin()
undici.getGlobalOrigin()Gets the global origin used in fetch.
Returns: URL
UrlObject
UrlObjectport
string | number(optional)path
string(optional)pathname
string(optional)hostname
string(optional)origin
string(optional)protocol
string(optional)search
string(optional)
Expect
Undici does not support the Expect request header field. The request body is always immediately sent and the 100 Continue response will be ignored.
Refs: https://tools.ietf.org/html/rfc7231#section-5.1.1
Pipelining
Undici will only use pipelining if configured with a pipelining factor greater than 1. Also it is important to pass blocking: false to the request options to properly pipeline requests.
Undici always assumes that connections are persistent and will immediately pipeline requests, without checking whether the connection is persistent. Hence, automatic fallback to HTTP/1.0 or HTTP/1.1 without pipelining is not supported.
Undici will immediately pipeline when retrying requests after a failed connection. However, Undici will not retry the first remaining requests in the prior pipeline and instead error the corresponding callback/promise/stream.
Undici will abort all running requests in the pipeline when any of them are aborted.
Refs: https://tools.ietf.org/html/rfc2616#section-8.1.2.2
Refs: https://tools.ietf.org/html/rfc7230#section-6.3.2
Manual Redirect
Since it is not possible to manually follow an HTTP redirect on the server-side, Undici returns the actual response instead of an opaqueredirect filtered one when invoked with a manual redirect. This aligns fetch() with the other implementations in Deno and Cloudflare Workers.
Refs: https://fetch.spec.whatwg.org/#atomic-http-redirect-handling
Workarounds
Network address family autoselection.
If you experience problem when connecting to a remote server that is resolved by your DNS servers to a IPv6 (AAAA record) first, there are chances that your local router or ISP might have problem connecting to IPv6 networks. In that case undici will throw an error with code UND_ERR_CONNECT_TIMEOUT.
If the target server resolves to both a IPv6 and IPv4 (A records) address and you are using a compatible Node version (18.3.0 and above), you can fix the problem by providing the autoSelectFamily option (support by both undici.request and undici.Agent) which will enable the family autoselection algorithm when establishing the connection.
Collaborators
Past Collaborators
Releasers
Long Term Support
Undici aligns with the Node.js LTS schedule. The following table shows the supported versions:
5.x
v18.x
2024-04-30
6.x
v20.x v22.x
2026-04-30
7.x
v24.x
2027-04-30
License
MIT
Last updated