### H2CClient Connection and Request Example Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/H2CClient.md Demonstrates how to create an H2CClient, listen for the 'connect' event, and perform a basic GET request. This example requires setting up an HTTP/2 server and then connecting to it. ```javascript import { createServer } from 'node:http2' import { once } from 'node:events' import { H2CClient } from 'undici' const server = createServer((request, response) => { response.end('Hello, World!') }).listen() await once(server, 'listening') const client = new H2CClient(`http://localhost:${server.address().port}`) client.on('connect', (origin) => { console.log(`Connected to ${origin}`) }) const { body } = await client.request({ path: '/', method: 'GET' }) console.log(await body.text()) client.close() server.close() ``` -------------------------------- ### Install undici APIs globally (CommonJS) Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/GlobalInstallation.md This CommonJS example demonstrates how to install undici's APIs globally. ```cjs const { install } = require('undici') install() ``` -------------------------------- ### Installing and Using Undici Module Source: https://github.com/nodejs/undici/blob/main/docs/docs/index.md Shows how to install the undici package and use its `request` and `fetch` APIs, including configuring a global dispatcher. ```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'); ``` -------------------------------- ### MockClient Request Example Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/MockClient.md Demonstrates how to use MockClient.request to intercept and respond to a GET request. Ensure MockAgent is configured with the correct number of connections. ```mjs import { MockAgent } from 'undici' const mockAgent = new MockAgent({ connections: 1 }) const mockClient = mockAgent.get('http://localhost:3000') mockClient.intercept({ path: '/foo' }).reply(200, 'foo') const { statusCode, body } = await mockClient.request({ origin: 'http://localhost:3000', path: '/foo', method: 'GET' }) console.log('response received', statusCode) // response received 200 for await (const data of body) { console.log('data', data.toString('utf8')) // data foo } ``` -------------------------------- ### Pairing fetch and FormData with global installation Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/GlobalInstallation.md When using `FormData` as a request body, ensure it's paired with `fetch` from the same source. Global installation handles this automatically by making both resolve to undici. ```mjs import { install } from 'undici' install() const body = new FormData() await fetch('https://example.com', { method: 'POST', body }) ``` -------------------------------- ### BalancedPool Usage Example Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/BalancedPool.md Demonstrates how to create a BalancedPool with multiple upstreams and make a request. ```APIDOC ## BalancedPool Usage Example ### Description This example shows how to instantiate a `BalancedPool` with an array of upstream origins and then use its `request` method to send a GET request to the root path. It also demonstrates how to consume the response body. ### Code ```mjs import { BalancedPool } from 'undici' const pool = new BalancedPool([ 'http://localhost:3000', 'http://localhost:3001', 'http://localhost:3002', ]) const { statusCode, body } = await pool.request({ path: '/', method: 'GET', }) console.log('response received', statusCode) for await (const chunk of body) { console.log('data', chunk.toString()) } ``` ``` -------------------------------- ### Install undici using npm Source: https://github.com/nodejs/undici/blob/main/README.md Install the undici package using npm. This is the first step to using undici in your Node.js project. ```bash npm i undici ``` -------------------------------- ### Install Undici Globals for Fetch and FormData Source: https://github.com/nodejs/undici/blob/main/README.md Installs undici's implementations of `fetch`, `Headers`, `Response`, `Request`, `FormData`, and WebSocket-related globals. This allows using undici's versions with standard global calls. ```javascript import { install } from 'undici' install() const body = new FormData() body.set('name', 'some') await fetch('https://example.com', { method: 'POST', body }) ``` -------------------------------- ### Instantiate global APIs with undici Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/GlobalInstallation.md After calling `install()`, you can instantiate global APIs like Headers, Request, FormData, WebSocket, and EventSource directly. These will use undici's implementations. ```mjs import { install } from 'undici' install() 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') ``` -------------------------------- ### Perform a simple GET request Source: https://github.com/nodejs/undici/blob/main/docs/examples/README.md Demonstrates how to execute a basic GET request using Undici and read the response body as plain text. ```javascript const { request } = require('undici') async function getRequest (port = 3001) { const { statusCode, headers, body } = await request(`http://localhost:${port}/`) const data = await body.text() console.log('response received', statusCode) console.log('headers', headers) console.log('data', data) } ``` -------------------------------- ### Conditional global installation of fetch Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/GlobalInstallation.md Guard the `install()` call to only replace the global `fetch` if it's not already defined. This prevents overwriting existing global fetch implementations. ```mjs import { install } from 'undici' if (typeof globalThis.fetch === 'undefined') { install() } const response = await fetch('https://example.com') ``` -------------------------------- ### Making a Request with Pool Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/Pool.md Demonstrates how to create a Pool, make a GET request, and then close the pool. Ensure the server is running at http://localhost:3000. ```javascript import { Pool } from 'undici' const pool = new Pool('http://localhost:3000', { connections: 10 }) const { statusCode, headers, body } = await pool.request({ path: '/', method: 'GET' }) console.log(statusCode, headers) console.log(await body.text()) await pool.close() ``` -------------------------------- ### Basic Client Usage Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/Client.md Instantiate a Client for a specific origin and make a GET request. Ensure the 'undici' module is imported. ```mjs import { Client } from 'undici' const client = new Client('http://localhost:3000') const { statusCode, body } = await client.request({ path: '/', method: 'GET' }) ``` -------------------------------- ### Install Undici Web APIs Globally Source: https://github.com/nodejs/undici/blob/main/README.md Use this snippet to add Undici's web API implementations to `globalThis`. This allows you to use `fetch`, `Headers`, `Request`, `Response`, `FormData`, `WebSocket`, and `EventSource` without explicit imports after calling `install()`. ```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') ``` -------------------------------- ### H2CClient Usage Example Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/H2CClient.md Demonstrates how to instantiate and use the H2CClient to make a request to an http: origin. ```APIDOC ## H2CClient Usage Example ### Description This example shows how to create an instance of `H2CClient` and perform a basic GET request. ### Method `new H2CClient(origin, [options])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { H2CClient } from 'undici' const client = new H2CClient('http://localhost:3000') const { statusCode, body } = await client.request({ path: '/', method: 'GET' }) console.log(statusCode) console.log(await body.text()) ``` ### Response #### Success Response (200) - `statusCode` (number) - The HTTP status code of the response. - `body` (ReadableStream) - The response body as a readable stream. #### Response Example ```json { "example": "response body content" } ``` ### Error Handling - Passing a protocol other than `http:` to the `H2CClient` constructor will throw an `InvalidArgumentError`. ``` -------------------------------- ### Customize Global Fetch with Undici's install() Source: https://github.com/nodejs/undici/blob/main/docs/docs/getting-started.md Replace Node.js's built-in globals with Undici's implementation using the install() function. This makes global fetch, Headers, Response, Request, and FormData available from Undici. ```javascript import { install } from 'undici' install() // Global fetch, Headers, Response, Request, and FormData // now come from undici, not the Node.js bundle const res = await fetch('https://example.com') ``` -------------------------------- ### `dispatcher.connect(options[, callback])` Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/Dispatcher.md Starts two-way communications with a resource using the HTTP CONNECT method. It can be used with a callback or return a Promise. ```APIDOC ### `dispatcher.connect(options[, callback])` Starts two-way communications with the requested resource using the [HTTP `CONNECT`][] method. It can be used with a callback or return a Promise. * `options` {Object} * `origin` {string|URL} The origin to connect to. * `path` {string} The request path. * `headers` {UndiciHeaders} Request headers. **Default:** `null`. * `signal` {AbortSignal|EventEmitter|null} A signal used to abort the request. **Default:** `null`. * `opaque` {any} An opaque value passed through to the returned `ConnectData`. * `responseHeaders` {string|null} Set to `'raw'` to return the response headers as a raw array instead of an object. **Default:** `null`. * `callback` {Function} (optional) Invoked when the connection is established. * `error` {Error|null} * `data` {Object} * `statusCode` {number} * `headers` {Object} The response headers. * `socket` {Duplex} The established socket. * `opaque` {any} The `opaque` value passed in `options`. * Returns: {Promise} A `Promise` is returned only when `callback` is omitted. It resolves with the `data` object described above. ```mjs import { createServer } from 'node:http' import { Client } from 'undici' import { once } from 'node:events' const server = createServer((request, response) => { throw new Error('should never get here') }).listen() server.on('connect', (req, socket, head) => { socket.write('HTTP/1.1 200 Connection established\r\n\r\n') let data = head.toString() socket.on('data', (buf) => { data += buf.toString() }) socket.on('end', () => { socket.end(data) }) }) await once(server, 'listening') const client = new Client(`http://localhost:${server.address().port}`) try { const { socket } = await client.connect({ path: '/' }) const wanted = 'Body' let data = '' socket.on('data', d => { data += d }) socket.on('end', () => { console.log(`Data received: ${data.toString()} | Data wanted: ${wanted}`) client.close() server.close() }) socket.write(wanted) socket.end() } catch (error) {} ``` ``` -------------------------------- ### Install undici APIs globally (ES Module) Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/GlobalInstallation.md Use this to make undici's fetch, Headers, Response, etc. available globally without importing them first. This is useful for polyfilling environments. ```mjs import { install } from 'undici' install() // `fetch`, `Headers`, `Response`, `Request`, etc. now resolve to undici's // implementations. const response = await fetch('https://example.com') ``` -------------------------------- ### Configure DNS Interceptor with Options Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/Interceptors.md Example of configuring the DNS interceptor with custom options for maximum TTL, dual-stack preference, and IP affinity. ```javascript import { Agent, interceptors } from 'undici' const agent = new Agent().compose( interceptors.dns({ maxTTL: 60_000, // cache for at most 60 seconds dualStack: true, affinity: 4 // prefer IPv4 }) ) ``` -------------------------------- ### agent.loadSnapshots([filePath]) Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/SnapshotAgent.md Loads snapshots from disk into memory. In 'playback' mode, this also installs the corresponding MockAgent interceptors to match subsequent requests against the loaded snapshots. ```APIDOC ## agent.loadSnapshots([filePath]) ### Description Loads snapshots from disk into memory. In 'playback' mode this also installs the corresponding [`MockAgent`][] interceptors so that subsequent requests are matched against the loaded snapshots. ### Method * `filePath` {string} (optional) Path to read snapshots from. **Default:** the `snapshotPath` given to the constructor. ### Returns * {Promise} Resolves when the snapshots have been loaded. ### Example ```mjs await agent.loadSnapshots('./snapshots/api.json') ``` ``` -------------------------------- ### Perform an HTTP Request with Undici Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/Dispatcher.md Demonstrates how to perform a basic HTTP GET request using `client.request` and handle the response. Ensure the server and client are properly closed after use. ```mjs import { createServer } from 'node:http' import { Client } from 'undici' import { once } from 'node:events' const server = createServer((request, response) => { response.end('Hello, World!') }).listen() await once(server, 'listening') const client = new Client(`http://localhost:${server.address().port}`) try { const { body, headers, statusCode, statusText, trailers } = await client.request({ path: '/', method: 'GET' }) console.log(`response received ${statusCode}`) console.log('headers', headers) body.setEncoding('utf8') body.on('data', console.log) body.on('error', console.error) body.on('end', () => { console.log('trailers', trailers) }) client.close() server.close() } catch (error) { console.error(error) } ``` -------------------------------- ### Importing fetch and FormData directly from undici Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/GlobalInstallation.md If global installation is not desired, you can import `fetch` and `FormData` directly from 'undici' to ensure they are paired correctly. ```mjs import { fetch, FormData } from 'undici' const body = new FormData() await fetch('https://example.com', { method: 'POST', body }) ``` -------------------------------- ### Client Instantiation with Custom DNS Lookup Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/Client.md Provide a custom DNS lookup function to control how hostnames are resolved. This example forces IPv4 resolution. ```mjs import { Client } from 'undici' import dns from 'node:dns' const client = new Client('https://example.com', { connect: { lookup (hostname, options, callback) { dns.lookup(hostname, { ...options, family: 4 }, callback) } } }) ``` -------------------------------- ### pool.request Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/Pool.md Performs a request through one of the pooled clients. Includes an example of making a GET request and handling the response. ```APIDOC ## `pool.request(options[, callback])` ### Description See [`dispatcher.request(options[, callback])`][]. Performs a request through one of the pooled clients. ### Method `request` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```mjs import { Pool } from 'undici' const pool = new Pool('http://localhost:3000', { connections: 10 }) const { statusCode, headers, body } = await pool.request({ path: '/', method: 'GET' }) console.log(statusCode, headers) console.log(await body.text()) await pool.close() ``` ### Response None ERROR HANDLING: None ``` -------------------------------- ### Initialize MockAgent and MockClient (MJS) Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/MockClient.md Demonstrates how to initialize a MockAgent with a single connection to obtain a MockClient instance in an MJS environment. ```mjs import { MockAgent } from 'undici' // `connections: 1` makes the agent hand out `MockClient` instances. const mockAgent = new MockAgent({ connections: 1 }) const mockClient = mockAgent.get('http://localhost:3000') ``` -------------------------------- ### Making HTTP Requests with Undici Client Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/Dispatcher.md Demonstrates making a GET request using the `client.dispatch` method and handling various lifecycle events like connection, response start, data, and end. This is useful for general API interactions. ```mjs import { createServer } from 'node:http' import { Client } from 'undici' import { once } from 'node:events' const server = createServer((request, response) => { response.end('Hello, World!') }).listen() await once(server, 'listening') const client = new Client(`http://localhost:${server.address().port}`) const data = [] client.dispatch({ path: '/', method: 'GET', headers: { 'x-foo': 'bar' } }, { onRequestStart: () => { console.log('Connected!') }, onResponseError: (_controller, error) => { console.error(error) }, onResponseStart: (_controller, statusCode, headers) => { console.log(`statusCode: ${statusCode} | headers: ${JSON.stringify(headers)}`) }, onResponseData: (_controller, chunk) => { data.push(chunk) }, onResponseEnd: (_controller, trailers) => { console.log(`trailers: ${JSON.stringify(trailers)}`) console.log(`Data: ${Buffer.concat(data).toString('utf8')}`) client.close() server.close() } }) ``` -------------------------------- ### Create MockAgent and MockPool (MJS) Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/MockPool.md Demonstrates how to import MockAgent and create a MockPool for a specific origin using MJS syntax. ```mjs import { MockAgent } from 'undici' const mockAgent = new MockAgent() const mockPool = mockAgent.get('http://localhost:3000') ``` -------------------------------- ### Minimal RetryHandler with Default Options Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/RetryHandler.md This example shows a minimal RetryHandler configuration that relies on the default retry options. It sets up the basic dispatch and handler callbacks without custom retry logic. ```mjs import { Client, RetryHandler } from 'undici' const client = new Client(`http://localhost:${server.address().port}`) const handler = new RetryHandler(dispatchOptions, { dispatch: client.dispatch.bind(client), handler: { onRequestStart () {}, onResponseStart (controller, status, headers) {}, onResponseData (controller, chunk) {}, onResponseEnd () {}, onResponseError (controller, err) {} } }) client.dispatch(dispatchOptions, handler) ``` -------------------------------- ### Simple GET Request Source: https://github.com/nodejs/undici/blob/main/docs/examples/README.md Demonstrates how to perform a simple GET request and read the response body as text. ```APIDOC ## GET / ### Description Performs a simple GET request to the root endpoint and reads the response body as text. ### Method GET ### Endpoint `/ ### Parameters None ### Request Example ```javascript const { request } = require('undici') async function getRequest (port = 3001) { const { statusCode, headers, body } = await request(`http://localhost:${port}/`) const data = await body.text() console.log('response received', statusCode) console.log('headers', headers) console.log('data', data) } ``` ### Response #### Success Response (200) - **statusCode** (number) - The HTTP status code of the response. - **headers** (object) - The response headers. - **body** (ReadableStream) - The response body stream. #### Response Example ```json { "statusCode": 200, "headers": { ... }, "data": "response body as text" } ``` ``` -------------------------------- ### Client Instantiation Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/Client.md Demonstrates basic instantiation of the Client class with a URL. The connection is established lazily upon the first request. ```APIDOC ## Client Instantiation ### Description Instantiates a new `Client` object. The connection to the specified origin is established lazily when the first request is made. ### Usage ```javascript import { Client } from 'undici' const client = new Client('http://localhost:3000') ``` ### Options - `url` {string} The origin URL for the client. - `options` {object} (optional) Configuration options for the client. ``` -------------------------------- ### Install Undici Module Source: https://github.com/nodejs/undici/blob/main/README.md Installs the undici package as a separate dependency using npm. This provides access to the latest features and APIs. ```bash npm install undici ``` -------------------------------- ### Initialize Agent and Set Global Dispatcher Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/Agent.md Demonstrates how to create a new Agent instance with a specified number of connections and set it as the global dispatcher for all subsequent requests. ```mjs import { Agent, setGlobalDispatcher } from 'undici' const agent = new Agent({ connections: 10 }) setGlobalDispatcher(agent) ``` -------------------------------- ### MockClient Initialization Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/MockClient.md Demonstrates how to obtain a MockClient instance from a MockAgent configured for a single connection. ```APIDOC ## MockClient Initialization ### Description A `MockClient` is obtained from a `MockAgent` when the agent is configured with `connections: 1`. This allows for intercepting requests made through the client. ### Usage ```mjs import { MockAgent } from 'undici' // `connections: 1` makes the agent hand out `MockClient` instances. const mockAgent = new MockAgent({ connections: 1 }) const mockClient = mockAgent.get('http://localhost:3000') ``` ```cjs const { MockAgent } = require('undici') const mockAgent = new MockAgent({ connections: 1 }) const mockClient = mockAgent.get('http://localhost:3000') ``` ``` -------------------------------- ### Instantiate ProxyAgent with URI String or URL Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/ProxyAgent.md Demonstrates creating a ProxyAgent instance using a proxy URI provided as a string or a URL object. This is the most basic way to set up a proxy. ```mjs import { ProxyAgent } from 'undici' // A string or URL is treated as the proxy uri. const a = new ProxyAgent('http://localhost:8000') const b = new ProxyAgent(new URL('http://localhost:8000')) ``` -------------------------------- ### Making an HTTP GET Request with Client.request Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/Client.md Performs an HTTP GET request and streams the response body. This is a common use case for fetching data from a server. ```mjs import { Client } from 'undici' const client = new Client('http://localhost:3000') const { statusCode, headers, body } = await client.request({ path: '/', method: 'GET' }) console.log(statusCode) for await (const chunk of body) { console.log(chunk.toString()) } ``` -------------------------------- ### Create MockAgent and MockPool (CJS) Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/MockPool.md Demonstrates how to import MockAgent and create a MockPool for a specific origin using CommonJS syntax. ```cjs const { MockAgent } = require('undici') const mockAgent = new MockAgent() const mockPool = mockAgent.get('http://localhost:3000') ``` -------------------------------- ### Instantiate Agent as Dispatcher Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/Dispatcher.md Demonstrates how to instantiate an Agent and verify it is an instance of Dispatcher. ```mjs import { Dispatcher, Agent } from 'undici' const dispatcher = new Agent() console.log(dispatcher instanceof Dispatcher) // true ``` -------------------------------- ### Initialize MockAgent and MockClient (CJS) Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/MockClient.md Demonstrates how to initialize a MockAgent with a single connection to obtain a MockClient instance in a CommonJS environment. ```cjs const { MockAgent } = require('undici') const mockAgent = new MockAgent({ connections: 1 }) const mockClient = mockAgent.get('http://localhost:3000') ``` -------------------------------- ### sqliteCacheStore.size Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/CacheStore.md Gets the current number of responses stored in the SQLite database. ```APIDOC ## sqliteCacheStore.size ### Description Gets the current number of responses stored in the SQLite database. ### Method `size` (getter) ### Endpoint None ### Parameters None ### Request Example None ### Response #### Success Response (number) * Type: {number} #### Response Example None ``` -------------------------------- ### Creating and Using a BalancedPool Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/BalancedPool.md Demonstrates how to initialize a BalancedPool with multiple upstream origins and make a request. The pool automatically distributes requests across the provided upstreams. ```mjs import { BalancedPool } from 'undici' const pool = new BalancedPool([ 'http://localhost:3000', 'http://localhost:3001', 'http://localhost:3002', ]) const { statusCode, body } = await pool.request({ path: '/', method: 'GET', }) console.log('response received', statusCode) for await (const chunk of body) { console.log('data', chunk.toString()) } ``` -------------------------------- ### Opening and Listing Caches Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/CacheStorage.md Demonstrates opening a cache and then retrieving a list of all existing cache names. This is useful for managing multiple caches within an application. ```mjs import { caches } from 'undici' await caches.open('v1') console.log(await caches.keys()) // ['v1'] ``` -------------------------------- ### Initialize and Record with SnapshotAgent Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/SnapshotAgent.md Initializes a SnapshotAgent in 'record' mode, sets it as the global dispatcher, fetches data, and then closes the agent. Ensure the snapshotPath is correctly configured. ```mjs import { SnapshotAgent, setGlobalDispatcher, fetch } from 'undici' const agent = new SnapshotAgent({ mode: 'record', snapshotPath: './snapshots/api.json' }) setGlobalDispatcher(agent) const response = await fetch('https://api.example.com/users') const users = await response.json() await agent.close() ``` -------------------------------- ### Get All Recorded Call History Logs Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/MockCallHistory.md Retrieve all recorded MockCallHistoryLog entries in the order they were intercepted. ```mjs mockAgent.getCallHistory()?.calls() ``` -------------------------------- ### Client Certificate Authentication Example Source: https://github.com/nodejs/undici/blob/main/docs/docs/best-practices/client-certificate.md This snippet demonstrates setting up an HTTPS server that requests and verifies client certificates, and an Undici client that provides its own certificate for authentication. The server checks the `authorized` and `authorizationError` properties on the incoming request's client object. ```javascript const { readFileSync } = require('node:fs') const { join } = require('node:path') const { createServer } = require('node:https') const { Client } = require('undici') const serverOptions = { ca: [ readFileSync(join(__dirname, 'client-ca-crt.pem'), 'utf8') ], key: readFileSync(join(__dirname, 'server-key.pem'), 'utf8'), cert: readFileSync(join(__dirname, 'server-crt.pem'), 'utf8'), requestCert: true, rejectUnauthorized: false } const server = createServer(serverOptions, (req, res) => { // true if client cert is valid if(req.client.authorized === true) { console.log('valid') } else { console.error(req.client.authorizationError) } res.end() }) server.listen(0, function () { const tls = { ca: [ readFileSync(join(__dirname, 'server-ca-crt.pem'), 'utf8') ], key: readFileSync(join(__dirname, 'client-key.pem'), 'utf8'), cert: readFileSync(join(__dirname, 'client-crt.pem'), 'utf8'), rejectUnauthorized: false, servername: 'agent1' } const client = new Client(`https://localhost:${server.address().port}`, { connect: tls }) client.request({ path: '/', method: 'GET' }, (err, { body }) => { body.on('data', (buf) => {}) body.on('end', () => { client.close() server.close() }) }) }) ``` -------------------------------- ### GetResult Structure Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/CacheStore.md The result returned by the get method, containing all fields of CacheValue plus the response body. ```javascript { ...CacheValue, body: Readable|Iterable|AsyncIterable|Buffer|string } ``` -------------------------------- ### install() Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/GlobalInstallation.md Overwrites globalThis properties with undici's implementations of fetch, Headers, Response, Request, FormData, WebSocket, CloseEvent, ErrorEvent, MessageEvent, and EventSource. This ensures a consistent set of APIs across Node.js versions and satisfies third-party libraries. ```APIDOC ## install() ### Description Overwrites the following properties of `globalThis` with undici's implementations: * `globalThis.fetch` * `globalThis.Headers` * `globalThis.Response` * `globalThis.Request` * `globalThis.FormData` * `globalThis.WebSocket` * `globalThis.CloseEvent` * `globalThis.ErrorEvent` * `globalThis.MessageEvent` * `globalThis.EventSource` ### Returns * {undefined} ### Usage ```mjs import { install } from 'undici' install() // Now you can use fetch, Headers, Response, etc. directly const response = await fetch('https://example.com') 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') ``` ### Conditional Installation `install()` can be guarded so undici's `fetch` is only installed when no global `fetch` already exists: ```mjs import { install } from 'undici' if (typeof globalThis.fetch === 'undefined') { install() } const response = await fetch('https://example.com') ``` ### Pairing `fetch` and `FormData` When a request body is a `FormData` instance, the `fetch` and `FormData` implementations must come from the same source. After `install()`, both globals resolve to undici, so they always match: ```mjs import { install } from 'undici' install() const body = new FormData() await fetch('https://example.com', { method: 'POST', body }) ``` If global installation is not desired, import the matching pair directly from `'undici'` instead: ```mjs import { fetch, FormData } from 'undici' const body = new FormData() await fetch('https://example.com', { method: 'POST', body }) ``` Mixed usage can produce surprising multipart behavior across Node.js and undici versions. Keep the two paired. ``` -------------------------------- ### webSocketStream.close([closeInfo]) Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/WebSocket.md Starts the closing handshake for the WebSocket connection. Optionally accepts close code and reason. ```APIDOC ## webSocketStream.close([closeInfo]) ### Description Starts the closing handshake. When `closeInfo` is omitted, the connection is closed without a status code. ### Parameters #### Path Parameters * `closeInfo` (Object) - Optional - Information about the closure. * `closeCode` (number) - Optional - The status code to close with. * `reason` (string) - Optional - The reason to close with. **Default:** `''`. ``` -------------------------------- ### Basic Client Instantiation Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/Client.md Instantiate a Client with a base URL. The connection is established lazily when the first request is made. ```mjs import { Client } from 'undici' const client = new Client('http://localhost:3000') ``` -------------------------------- ### Basic Fetch Request Source: https://github.com/nodejs/undici/blob/main/docs/docs/getting-started.md Make a GET request to a URL and parse the JSON response using the fetch API. ```mjs import { fetch } from 'undici' const res = await fetch('https://example.com') const data = await res.json() console.log(data) ``` -------------------------------- ### Client Constructor Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/Client.md Initializes a new Client instance to connect to a specified origin. Options can be provided to configure various timeouts, connection behavior, and request limits. ```APIDOC ## new Client(url[, options]) ### Parameters * `url` {URL|string} - The origin to connect to. Only the protocol, hostname, and port are used. * `options` {Object} - Optional configuration object: * `bodyTimeout` {number|null} - Timeout in milliseconds for receiving body data between chunks. Default: `300e3`. * `headersTimeout` {number|null} - Timeout in milliseconds for receiving complete HTTP headers. Default: `300e3`. * `connectTimeout` {number|null} - Timeout in milliseconds for establishing a socket connection. Default: `10e3`. * `keepAliveTimeout` {number|null} - Timeout in milliseconds for a socket with no active requests. Default: `4e3`. * `keepAliveMaxTimeout` {number|null} - Maximum allowed `keepAliveTimeout` when overridden by server hints. Default: `600e3`. * `keepAliveTimeoutThreshold` {number|null} - Milliseconds subtracted from server keep-alive hints. Default: `2e3`. * `maxHeaderSize` {number|null} - Maximum request header size in bytes. Default: Node.js `--max-http-header-size` or `16384`. * `maxResponseSize` {number|null} - Maximum response body size in bytes. Set to `-1` to disable. Default: `-1`. * `maxRequestsPerClient` {number|null} - Maximum requests over a single connection before socket reset. `0` to disable. Default: `null`. * `localAddress` {string|null} - Local IP address for the socket connection. Default: `null`. * `pipelining` {number|null} - Number of concurrent requests over a single connection. `0` to disable keep-alive. Default: `1`. * `connect` {Object|Function|null} - Configures connection establishment. Accepts `ConnectOptions` or a custom connector function. * `socketPath` {string|null} - IPC endpoint (Unix domain socket or Windows named pipe). Default: `null`. * `maxCachedSessions` {number|null} - Maximum cached TLS sessions. `0` to disable. Default: `100`. * `timeout` {number|null} - Connection timeout in milliseconds. Default: `10e3`. * `servername` {string|null} - TLS server name for SNI. * `keepAlive` {boolean|null} - Enable TCP keep-alive. Default: `true`. * `keepAliveInitialDelay` {number|null} - TCP keep-alive interval in milliseconds. Default: `60000`. * `strictContentLength` {boolean} - Throw if request `content-length` mismatches body length. Default: `true`. * `autoSelectFamily` {boolean} - Enable family autodetection algorithm (RFC 8305). Ignored if unsupported. ``` -------------------------------- ### Get the Last Call History Log Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/MockCallHistory.md Retrieve the last recorded MockCallHistoryLog. Returns undefined if no logs exist. ```mjs mockAgent.getCallHistory()?.lastCall() ``` -------------------------------- ### Initialize MemoryCacheStore and set global dispatcher Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/CacheStore.md Demonstrates how to create a MemoryCacheStore with a specified maximum size and integrate it with Undici's caching interceptors and global dispatcher. ```mjs import { interceptors, cacheStores, Agent, setGlobalDispatcher } from 'undici' const store = new cacheStores.MemoryCacheStore({ maxSize: 50 * 1024 * 1024 }) setGlobalDispatcher( new Agent().compose(interceptors.cache({ store })) ) ``` -------------------------------- ### Get the First Call History Log Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/MockCallHistory.md Retrieve the first recorded MockCallHistoryLog. Returns undefined if no logs exist. ```mjs mockAgent.getCallHistory()?.firstCall() ``` -------------------------------- ### MemoryCacheStore Methods Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/CacheStore.md Core methods for interacting with the cache store, including getting, creating, and deleting cached entries. ```APIDOC ## MemoryCacheStore Methods ### `get(key)` * `key` {CacheKey} - The request to look up. See [`CacheKey`](#cachekey). * Returns: {GetResult|undefined} - The matching cached response, or `undefined` when there is no fresh entry for `key`. See [`GetResult`](#getresult). Looks up a cached response for `key`. A stored entry matches only when its `method` equals `key.method`, its `deleteAt` time is in the future, and every header listed in its `vary` map matches the corresponding header in `key.headers`. ### `createWriteStream(key, value)` * `key` {CacheKey} - The request the response is being cached for. See [`CacheKey`](#cachekey). * `value` {CacheValue} - The response metadata to store. See [`CacheValue`](#cachevalue). * Returns: {Writable|undefined} - A writable stream that the response body is written to, or `undefined` when the response cannot be cached. Returns a {Writable} stream used to write the response body into the store. When the stream finishes, the entry is committed; if its accumulated size exceeds `maxEntrySize`, the stream is destroyed and nothing is stored. Writing a new entry whose `key` matches an existing one replaces that entry. ### `delete(key)` * `key` {CacheKey} - The request whose cached responses should be removed. See [`CacheKey`](#cachekey). * Returns: {undefined} Removes every cached response stored for `key.origin` and `key.path`. Throws a `TypeError` if `key` is not an object. ``` -------------------------------- ### Check Undici Version in Node.js Source: https://github.com/nodejs/undici/blob/main/README.md Use this snippet to check the version of undici bundled with your current Node.js installation. ```javascript console.log(process.versions.undici); ``` -------------------------------- ### Instantiate ProxyAgent with Options Object Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/ProxyAgent.md Shows how to create a ProxyAgent instance using an options object, which requires the `uri` property to specify the proxy server's address. ```mjs import { ProxyAgent } from 'undici' // An options object requires a `uri`. const c = new ProxyAgent({ uri: 'http://localhost:8000' }) ``` -------------------------------- ### Get the Nth Call History Log Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/MockCallHistory.md Retrieve a specific MockCallHistoryLog by its 1-based position. Throws an error for invalid positions. ```mjs mockAgent.getCallHistory()?.nthCall(3) // the third recorded log ``` -------------------------------- ### Basic Fetch Usage Source: https://github.com/nodejs/undici/blob/main/README.md Demonstrates the basic usage of the undici fetch function to make a GET request and process the JSON response. ```APIDOC ## `undici.fetch(input[, init]): Promise` ### Description Implements the standard fetch API. ### Method GET (default) ### Endpoint [URL provided in input] ### Request Example ```js import { fetch } from 'undici' const res = await fetch('https://example.com') const json = await res.json() console.log(json) ``` ### Response #### Success Response (200) - **body** (ReadableStream) - The response body as a web stream. ### Response Example ```js // Assuming the response is JSON const json = await res.json() console.log(json) ``` ``` -------------------------------- ### Establish Connection with HTTP CONNECT Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/Dispatcher.md Demonstrates using the connect() method to establish two-way communication with a resource using the HTTP CONNECT method. The server must respond with '200 Connection established' for the connection to succeed. ```mjs import { createServer } from 'node:http' import { Client } from 'undici' import { once } from 'node:events' const server = createServer((request, response) => { throw new Error('should never get here') }).listen() server.on('connect', (req, socket, head) => { socket.write('HTTP/1.1 200 Connection established\r\n\r\n') let data = head.toString() socket.on('data', (buf) => { data += buf.toString() }) socket.on('end', () => { socket.end(data) }) }) await once(server, 'listening') const client = new Client(`http://localhost:${server.address().port}`) try { const { socket } = await client.connect({ path: '/' }) const wanted = 'Body' let data = '' socket.on('data', d => { data += d }) socket.on('end', () => { console.log(`Data received: ${data.toString()} | Data wanted: ${wanted}`) client.close() server.close() }) socket.write(wanted) socket.end() } catch (error) {} ``` -------------------------------- ### Perform Basic HTTP Request with Undici Source: https://github.com/nodejs/undici/blob/main/README.md A simple example demonstrating how to make a basic HTTP request using the `request` function from undici. It shows how to access status code, headers, trailers, and the response body. ```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) ``` -------------------------------- ### Convert MockCallHistoryLog to String Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/MockCallHistoryLog.md Get a string representation of the MockCallHistoryLog, useful for debugging. Object properties like searchParams and headers are JSON-stringified. ```mjs mockAgent.getCallHistory()?.firstCall()?.toString() ``` -------------------------------- ### Destroying a Client and Handling Pending Requests Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/Dispatcher.md Shows how to create an HTTP server and client, dispatch a request, and then destroy the client. The destruction process aborts pending requests and logs a confirmation message before closing the server. ```mjs import { createServer } from 'node:http' import { Client } from 'undici' import { once } from 'node:events' const server = createServer((request, response) => { response.end() }).listen() await once(server, 'listening') const client = new Client(`http://localhost:${server.address().port}`) try { const request = client.request({ path: '/', method: 'GET' }) client.destroy() .then(() => { console.log('Client destroyed') server.close() }) await request } catch (error) { console.error(error) } ``` -------------------------------- ### Get Hash from MockCallHistoryLog Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/MockCallHistoryLog.md Retrieve the hash fragment of an intercepted request from a MockCallHistoryLog instance. This method returns a Map representation of the log. ```mjs mockAgent.getCallHistory()?.firstCall()?.toMap().get('hash') ``` -------------------------------- ### Basic HTTP Request with Undici Source: https://github.com/nodejs/undici/blob/main/docs/docs/index.md Performs a basic HTTP request and streams the response body. Ensure 'undici' is installed as a module. ```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) ``` -------------------------------- ### Instantiate and Use H2CClient Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/H2CClient.md Demonstrates how to create an H2CClient instance and make a request. Ensure the server supports cleartext HTTP/2. ```mjs import { H2CClient } from 'undici' const client = new H2CClient('http://localhost:3000') const { statusCode, body } = await client.request({ path: '/', method: 'GET' }) console.log(statusCode) console.log(await body.text()) ``` -------------------------------- ### Importing Fetch from Undici Source: https://github.com/nodejs/undici/blob/main/docs/docs/best-practices/undici-vs-builtin-fetch.md Import `fetch` directly from the 'undici' package to use your installed version instead of the built-in global one. ```javascript import { fetch } from 'undici' // uses your installed version, not the built-in ``` -------------------------------- ### Function to Mock Source: https://github.com/nodejs/undici/blob/main/docs/docs/best-practices/mocking-request.md This is an example of a function that makes an HTTP POST request using Undici. This function will be the target of our mocking in the test file. ```js // bank.mjs import { request } from 'undici' export async function bankTransfer(recipient, amount) { const { body } = await request('http://localhost:3000/bank-transfer', { method: 'POST', headers: { 'X-TOKEN-SECRET': 'SuperSecretToken', }, body: JSON.stringify({ recipient, amount }) } ) return await body.json() } ``` -------------------------------- ### Dispatcher Class Overview Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/Dispatcher.md Demonstrates how to instantiate a concrete dispatcher (Agent) and verify it inherits from Dispatcher. ```APIDOC ## Class: `Dispatcher` Base dispatcher class. Concrete dispatchers extend it and implement the [`dispatch()`][] method on which the other request helpers are built. ```mjs import { Dispatcher, Agent } from 'undici' const dispatcher = new Agent() console.log(dispatcher instanceof Dispatcher) // true ``` ``` -------------------------------- ### redirectHandler.onRequestStart Source: https://github.com/nodejs/undici/blob/main/docs/docs/api/RedirectHandler.md Forwards the request-start event to the wrapped handler, augmenting the context with redirect history. ```APIDOC ## redirectHandler.onRequestStart(controller, context) ### Description Forwards the request-start event to the wrapped handler, augmenting the context with redirect history. ### Parameters * `controller` {DispatchController} - The controller for the in-flight request. * `context` {Object} - The dispatch context. ``` -------------------------------- ### undici.connect Source: https://github.com/nodejs/undici/blob/main/README.md Starts two-way communications with the requested resource using HTTP CONNECT. It returns a promise that resolves with the result of the Dispatcher.connect method. ```APIDOC ## undici.connect([url, options]): Promise ### Description Starts two-way communications with the requested resource using [HTTP CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT). ### Parameters * **url** `string | URL | UrlObject` - The URL to connect to. * **options** `ConnectOptions` - Configuration options for the connection. * **dispatcher** `Dispatcher` - The dispatcher to use for the connection. Defaults to the global dispatcher. * **callback** `(err: Error | null, data: ConnectData | null) => void` (optional) - A callback function to handle the connection result. ### Returns A promise with the result of the `Dispatcher.connect` method. ``` -------------------------------- ### Basic Fetch Request with Undici Source: https://github.com/nodejs/undici/blob/main/README.md Demonstrates how to perform a basic GET request using undici's fetch and parse the JSON response. ```javascript import { fetch } from 'undici' const res = await fetch('https://example.com') const json = await res.json() console.log(json) ```