### Installing and Using the Undici Module Source: https://undici.nodejs.org/index Shows how to install the undici module via npm and then use its APIs, including `request` for maximum performance and `fetch` with custom configurations like agents. It highlights the flexibility and advanced features available. ```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'); ``` -------------------------------- ### Global Installation Source: https://undici.nodejs.org/index Explains how to use the `install()` function to make Undici's WHATWG fetch classes globally available in Node.js environments. ```APIDOC ## Global Installation Undici provides an `install()` function to add all WHATWG fetch classes to `globalThis`, making them available globally: ```javascript import { install } from 'undici' // Install all WHATWG fetch classes globally 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 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 ``` -------------------------------- ### Undici Basic Request Example Source: https://undici.nodejs.org/index Demonstrates a basic HTTP GET request using the `undici.request` function. It shows how to retrieve the status code, headers, trailers, and the response body, iterating through the body data. ```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) ``` -------------------------------- ### Global Installation of WHATWG Fetch Classes with Undici in Node.js Source: https://undici.nodejs.org/index Shows how to use Undici's `install()` function to make WHATWG fetch classes globally available in Node.js. This allows using `fetch`, `Headers`, `Request`, `FormData`, `WebSocket`, and `EventSource` without explicit imports. It's useful for polyfilling or ensuring consistent fetch behavior. ```javascript import { install } from 'undici' // Install all WHATWG fetch classes globally 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') ``` -------------------------------- ### Migrating from Built-in Fetch to Undici Source: https://undici.nodejs.org/index Provides a clear, step-by-step guide for migrating from Node.js's built-in fetch API to the undici module. It shows direct replacements for both `fetch` and introduces the `request` API for improved performance. ```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(); ``` -------------------------------- ### Dispatcher Management Source: https://undici.nodejs.org/index APIs for setting and getting the global dispatcher, which manages request dispatching. ```APIDOC ## Dispatcher Management ### `undici.setGlobalDispatcher(dispatcher)` #### Description Sets the global dispatcher used by common Undici API methods. This dispatcher is shared across compatible Undici modules. #### Parameters * **dispatcher** `Dispatcher` - The dispatcher to set as the global default. ### `undici.getGlobalDispatcher()` #### Description Gets the currently set global dispatcher. #### Returns `Dispatcher` - The global dispatcher instance. ``` -------------------------------- ### Using Undici HTTP Cache Interceptor in Node.js Source: https://undici.nodejs.org/index Demonstrates how to implement Undici's HTTP caching interceptor to cache responses based on HTTP caching best practices. It includes configuration for cache stores, size limits, and methods to cache. The example shows setting a global dispatcher and fetching data, with the second fetch being served from the cache. ```javascript import { fetch, Agent, interceptors, cacheStores } from 'undici'; // Create a client with cache interceptor const client = new Agent().compose(interceptors.cache({ // Optional: Configure cache store (defaults to MemoryCacheStore) store: new cacheStores.MemoryCacheStore({ maxSize: 100 * 1024 * 1024, // 100MB maxCount: 1000, maxEntrySize: 5 * 1024 * 1024 // 5MB }), // Optional: Specify which HTTP methods to cache (default: ['GET', 'HEAD']) methods: ['GET', 'HEAD'] })); // Set the global dispatcher to use our caching client setGlobalDispatcher(client); // Now all fetch requests will use the cache async function getData() { const response = await fetch('https://api.example.com/data'); // The server should set appropriate Cache-Control headers in the response // which the cache will respect based on the cache policy return response.json(); } // First request - fetches from origin const data1 = await getData(); // Second request - served from cache if within max-age const data2 = await getData(); ``` -------------------------------- ### Making HTTP Requests with undici.request in Node.js Source: https://undici.nodejs.org/index Provides an example of using the `undici.request` method to make HTTP requests in Node.js. It details the arguments for `url` and `options`, including parameters like `dispatcher` and `method`. The function returns a Promise that resolves with the result of the `Dispatcher.request` method. ```javascript import { request } from 'undici' // Example usage: const { body } = await request('http://localhost:3000/foo') const data = await body.json() console.log(data) ``` -------------------------------- ### Origin Management for fetch Source: https://undici.nodejs.org/index APIs for setting and getting the global origin used by the `fetch` function. ```APIDOC ## Origin Management ### `undici.setGlobalOrigin(origin)` #### Description Sets the global origin for `fetch` requests. This is useful for making relative requests to a specific base URL. #### Parameters * **origin** `string | URL | undefined` - The origin to set. If `undefined`, the global origin is reset, causing relative paths in `fetch`, `Request`, and `Response.redirect` to throw an error. #### Example ```javascript setGlobalOrigin('http://localhost:3000') const response = await fetch('/api/ping') console.log(response.url) // http://localhost:3000/api/ping ``` ### `undici.getGlobalOrigin()` #### Description Gets the currently set global origin for `fetch` requests. #### Returns `URL` - The global origin URL. ``` -------------------------------- ### Checking Bundled Undici Version Source: https://undici.nodejs.org/index A simple code snippet to display the version of undici that is bundled with the current Node.js installation. This is useful for understanding compatibility and feature availability. ```javascript console.log(process.versions.undici); ``` -------------------------------- ### Using Body Mixins with undici.request in Node.js Source: https://undici.nodejs.org/index Illustrates how to use body mixins like `.json()`, `.text()`, `.arrayBuffer()`, `.blob()`, and `.bytes()` to format the response body from `undici.request`. The example shows making a request and then parsing the body as JSON. It also notes that the body cannot be reused after a mixin is called. ```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) ``` -------------------------------- ### Common API Methods: undici.request Source: https://undici.nodejs.org/index Documents the `undici.request` method, detailing its arguments for URL, options (including dispatcher and method), and its return value. ```APIDOC ## 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` 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 Fetch with Basic Usage Source: https://undici.nodejs.org/index Demonstrates the basic usage of the fetch function in Undici to make an HTTP request and process the JSON response. It requires importing the fetch function from 'undici'. ```javascript import { fetch } from 'undici' const res = await fetch('https://example.com') const json = await res.json() console.log(json) ``` -------------------------------- ### Using Built-in Fetch in Node.js v18+ Source: https://undici.nodejs.org/index Demonstrates how to use the globally available fetch API in Node.js v18 and later, which is powered by a bundled version of undici. It shows a basic request and how to check the bundled undici version. ```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" ``` -------------------------------- ### Expect Header and Pipelining Behavior Source: https://undici.nodejs.org/index Explains Undici's handling of the 'Expect' header and its pipelining behavior for HTTP requests. ```APIDOC ## Header and Pipelining Behavior ### Expect Header Undici does not support the `Expect` request header. Request bodies are sent immediately, and `100 Continue` responses are ignored. ### Pipelining Undici utilizes HTTP pipelining when configured with a `pipelining` factor greater than `1` and `blocking: false` is set in request options. Automatic fallback to HTTP/1.0 or HTTP/1.1 without pipelining is not supported. Pipelining is also used when retrying requests after a connection failure, though the first remaining requests in the pipeline may error. Aborting any request in the pipeline will abort all running requests within that pipeline. * Refs: https://tools.ietf.org/html/rfc2616#section-8.1.2.2 * Refs: https://tools.ietf.org/html/rfc7230#section-6.3.2 ``` -------------------------------- ### undici.upgrade([url, options], callback) Source: https://undici.nodejs.org/index Allows upgrading to a different protocol, facilitating mechanisms like WebSockets. ```APIDOC ## `undici.upgrade([url, options], callback)` ### Description Upgrades the connection to a different protocol (e.g., WebSockets). This method calls `options.dispatcher.upgrade(options)`. ### Method `undici.upgrade ### Parameters * **url** `string | URL | UrlObject` - The URL to upgrade. * **options** `UpgradeOptions` - Configuration options for the upgrade. * **dispatcher** `Dispatcher` - The dispatcher to use. Defaults to `getGlobalDispatcher()`. * **callback** `(error: Error | null, data: UpgradeData) => void` (Optional) - A callback function to handle the result. ### Returns A promise that resolves with the result of the `Dispatcher.upgrade` method. ``` -------------------------------- ### Using Cache Interceptor Source: https://undici.nodejs.org/index Demonstrates how to configure and use Undici's HTTP caching interceptor to cache responses based on standard HTTP caching headers. ```APIDOC ## Using Cache Interceptor Undici provides a powerful HTTP caching interceptor that follows HTTP caching best practices. Here's how to use it: ```javascript import { fetch, Agent, interceptors, cacheStores } from 'undici'; // Create a client with cache interceptor const client = new Agent().compose(interceptors.cache({ // Optional: Configure cache store (defaults to MemoryCacheStore) store: new cacheStores.MemoryCacheStore({ maxSize: 100 * 1024 * 1024, // 100MB maxCount: 1000, maxEntrySize: 5 * 1024 * 1024 // 5MB }), // Optional: Specify which HTTP methods to cache (default: ['GET', 'HEAD']) methods: ['GET', 'HEAD'] })); // Set the global dispatcher to use our caching client setGlobalDispatcher(client); // Now all fetch requests will use the cache async function getData() { const response = await fetch('https://api.example.com/data'); // The server should set appropriate Cache-Control headers in the response // which the cache will respect based on the cache policy return response.json(); } // First request - fetches from origin const data1 = await getData(); // Second request - served from cache if within max-age const data2 = await getData(); ``` ### 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 ``` -------------------------------- ### undici.stream Source: https://undici.nodejs.org/index Initiates a stream for a given URL with optional configuration. It utilizes a dispatcher to handle the streaming process and returns a Promise resolving to the dispatcher's stream result. ```APIDOC ## undici.stream ### Description Initiates a stream for a given URL with optional configuration. It utilizes a dispatcher to handle the streaming process and returns a Promise resolving to the dispatcher's stream result. ### Method `undici.stream([url, options, ]factory): Promise` ### Parameters #### Path Parameters * **url** (string | URL | UrlObject) - The URL to stream from. * **options** (StreamOptions) - Optional configuration for the stream. * **dispatcher** (Dispatcher) - The dispatcher to use. Defaults to `getGlobalDispatcher()`. * **method** (String) - The HTTP method to use. Defaults to `PUT` if `options.body` is set, otherwise `GET`. * **factory** (Dispatcher.stream.factory) - The factory function for creating the stream. ### Response #### Success Response (Promise) - A Promise that resolves with the result of the `Dispatcher.stream` method. ### Notes Calls `options.dispatcher.stream(options, factory)`. See `Dispatcher.stream` for more details. ``` -------------------------------- ### Undici Fetch with Custom Dispatcher Source: https://undici.nodejs.org/index Shows how to use fetch with a custom dispatcher, such as an Agent with specific keep-alive options. This allows for more control over connection pooling and timeouts. It requires importing fetch and Agent from 'undici'. ```javascript import { fetch, Agent } from 'undici' const res = await fetch('https://example.com', { // Mocks are also supported dispatcher: new Agent({ keepAliveTimeout: 10, keepAliveMaxTimeout: 10 }) }) const json = await res.json() console.log(json) ``` -------------------------------- ### undici.pipeline Source: https://undici.nodejs.org/index Establishes a pipeline for two-way communication using HTTP CONNECT. It takes a URL, options, and a handler, returning a Duplex stream for managing the communication. ```APIDOC ## undici.pipeline ### Description Establishes a pipeline for two-way communication using HTTP CONNECT. It takes a URL, options, and a handler, returning a Duplex stream for managing the communication. ### Method `undici.pipeline([url, options, ]handler): Duplex` ### Parameters #### Path Parameters * **url** (string | URL | UrlObject) - The URL to establish a pipeline with. * **options** (PipelineOptions) - Optional configuration for the pipeline. * **dispatcher** (Dispatcher) - The dispatcher to use. Defaults to `getGlobalDispatcher()`. * **method** (String) - The HTTP method to use. Defaults to `PUT` if `options.body` is set, otherwise `GET`. * **handler** (Dispatcher.pipeline.handler) - The handler for the pipeline. ### Response #### Success Response (Duplex Stream) - Returns a `stream.Duplex` object for managing the pipeline. ### Notes Calls `options.dispatch.pipeline(options, handler)`. See `Dispatcher.pipeline` for more details. ``` -------------------------------- ### undici.connect Source: https://undici.nodejs.org/index Initiates two-way communication with a resource using the HTTP CONNECT method. It supports an optional callback function for handling connection results. ```APIDOC ## undici.connect ### Description Initiates two-way communication with a resource using the HTTP CONNECT method. It supports an optional callback function for handling connection results. ### Method `undici.connect([url, options]): Promise` ### Parameters #### Path Parameters * **url** (string | URL | UrlObject) - The URL to connect to. * **options** (ConnectOptions) - Optional configuration for the connection. * **dispatcher** (Dispatcher) - The dispatcher to use. Defaults to `getGlobalDispatcher()`. * **callback** ((err: Error | null, data: ConnectData | null) => void) - Optional callback function. ### Response #### Success Response (Promise) - A Promise that resolves with the result of the `Dispatcher.connect` method. ### Notes Calls `options.dispatch.connect(options)`. See `Dispatcher.connect` for more details. ``` -------------------------------- ### Set Global Origin for Fetch in Node.js Source: https://undici.nodejs.org/index Demonstrates how to set a global origin for fetch requests in Node.js using `setGlobalOrigin`, and shows the resulting full URL after a fetch. ```javascript setGlobalOrigin('http://localhost:3000') const response = await fetch('/api/ping') console.log(response.url) // http://localhost:3000/api/pingCopy CodeErrorCopied ``` -------------------------------- ### Body Mixins Source: https://undici.nodejs.org/index Details the body mixins available for formatting request and response bodies, including `.arrayBuffer()`, `.blob()`, `.json()`, and `.text()`. ```APIDOC ## 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()`. 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. ``` -------------------------------- ### undici.fetch Source: https://undici.nodejs.org/index Implements the standard Fetch API for making HTTP requests. It supports various request body types, including async iterables, and provides details on response body handling and duplex settings. ```APIDOC ## undici.fetch ### Description Implements the standard Fetch API for making HTTP requests. It supports various request body types, including async iterables, and provides details on response body handling and duplex settings. ### Method `undici.fetch(input[, init]): Promise` ### Parameters #### Path Parameters * **input** (string | URL | Request) - The resource to fetch. * **init** (RequestInit) - Optional settings for the request. * **body** (ArrayBuffer | ArrayBufferView | AsyncIterables | Blob | Iterables | String | URLSearchParams | FormData) - The request body. * **method** (String) - The HTTP method. * **duplex** ('half') - Required when `body` is `ReadableStream` or `Async Iterables`. * **dispatcher** (Dispatcher) - Optional dispatcher. ### Request Example ```javascript import { fetch } from 'undici' const res = await fetch('https://example.com') const json = await res.json() console.log(json) ``` ### Response #### Success Response (Response) - A `Response` object. #### Response Body - `response.body` returns a readable web stream. ### Notes - Supports `Async Iterables` for `request.body`. - `request.duplex` must be set to `'half'` for `ReadableStream` or `Async Iterables` bodies. - For Node streams, use `Readable.fromWeb(response.body)`. - Does not implement CORS checks by default (server-side behavior). ``` -------------------------------- ### Header Management in Undici Source: https://undici.nodejs.org/index Details how Undici handles forbidden and safelisted header names, differing from browser environments by offering more user control. ```APIDOC ## Header Management ### Description Undici provides more user control over headers compared to browser environments, where certain headers are forbidden or safelisted by the Fetch Standard. These constraints are removed in Undici. ### Forbidden and Safelisted Header Names Undici does not enforce the Fetch Standard's restrictions on forbidden and safelisted header names, allowing direct manipulation for requests and responses. ``` -------------------------------- ### Fetch Headers using HEAD Request in Node.js Source: https://undici.nodejs.org/index Shows how to efficiently retrieve only the headers of a resource using an HTTP HEAD request with the fetch API, avoiding response body consumption. ```javascript const headers = await fetch(url, { method: 'HEAD' }) .then(res => res.headers)Copy CodeErrorCopied ``` -------------------------------- ### Consume Response Body in Node.js Fetch Source: https://undici.nodejs.org/index Demonstrates the correct way to consume a response body in Node.js using the fetch API to prevent resource leaks, contrasting it with an incorrect approach. ```javascript // Do const { body, headers } = await fetch(url); for await (const chunk of body) { // force consumption of body } // Do not const { headers } = await fetch(url);Copy CodeErrorCopied ``` -------------------------------- ### Consume Response Body with Node.js Request Source: https://undici.nodejs.org/index Illustrates the mandatory consumption of the response body when using the `request` function in Undici, highlighting the correct method. ```javascript // Do const { body, headers } = await request(url); await res.body.dump(); // force consumption of body // Do not const { headers } = await request(url);Copy CodeErrorCopied ``` -------------------------------- ### UrlObject Definition Source: https://undici.nodejs.org/index Defines the structure of the UrlObject used in Undici for URL manipulation. ```APIDOC ## `UrlObject` Definition ### Description Represents a URL object with various components that can be specified. ### Fields * **port** `string | number` (Optional) * **path** `string` (Optional) * **pathname** `string` (Optional) * **hostname** `string` (Optional) * **origin** `string` (Optional) * **protocol** `string` (Optional) * **search** `string` (Optional) ``` -------------------------------- ### Undici Fetch with FormData and Blob Body Source: https://undici.nodejs.org/index Demonstrates sending a FormData object containing a Blob (created from a file stream) as the request body. This is useful for uploading files. It requires importing openAsBlob from 'node:fs'. ```javascript import { openAsBlob } from 'node:fs' const file = await openAsBlob('./big.csv') const body = new FormData() body.set('file', file, 'big.csv') await fetch('http://example.com', { method: 'POST', body }) ``` -------------------------------- ### Consuming and Cancelling Response Bodies Source: https://undici.nodejs.org/index Explains the importance of consuming or cancelling response bodies in Undici to manage connection resources effectively, especially compared to browser environments. ```APIDOC ## Consuming and Cancelling Response Bodies ### Description Properly handling response bodies is crucial in Undici to prevent excessive connection usage and performance degradation. Unlike browsers, Node.js's garbage collection is less predictable, making it essential to either consume or cancel response bodies. ### Consume Response Body ```javascript // Do const { body, headers } = await fetch(url); for await (const chunk of body) { // force consumption of body } ``` ### Do Not Consume Response Body ```javascript // Do not const { headers } = await fetch(url); ``` ### Using HEAD Request For retrieving only headers, the `HEAD` request method is recommended to avoid consuming the response body. ```javascript const headers = await fetch(url, { method: 'HEAD' }) .then(res => res.headers) ``` ### `request` API Consumption of the response body is mandatory when using the `request` API. ```javascript // Do const { body, headers } = await request(url); await res.body.dump(); // force consumption of body // Do not const { headers } = await request(url); ``` ``` -------------------------------- ### Undici Fetch Response Body Conversion to Node Stream Source: https://undici.nodejs.org/index Explains how to convert the web stream returned by `response.body` in Undici to a Node.js readable stream using `Readable.fromWeb()`. This is useful for compatibility with Node.js stream APIs. ```javascript import { fetch } from 'undici' import { Readable } from 'node:stream' const response = await fetch('https://example.com') const readableWebStream = response.body const readableNodeStream = Readable.fromWeb(readableWebStream) ``` -------------------------------- ### Undici Fetch with Async Iterable Body Source: https://undici.nodejs.org/index Illustrates sending an asynchronous iterable as the request body with Undici's fetch. This is a non-standard feature that supports streaming data. The 'duplex' option must be set to 'half' when using ReadableStream or Async Iterables. ```javascript import { fetch } from 'undici' const data = { async *[Symbol.asyncIterator]() { yield 'hello' yield 'world' }, } await fetch('https://example.com', { body: data, method: 'POST', duplex: 'half' }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.