From 546ddf24b515d23d50f3bcef4e66a8a2b0e598a6 Mon Sep 17 00:00:00 2001 From: Geoffrey Booth Date: Fri, 28 Mar 2025 18:48:40 -0700 Subject: [PATCH] Update DNS caching example to include other interceptors, production settings --- docs/examples/README.md | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/docs/examples/README.md b/docs/examples/README.md index a8a14cfc150..8bf3a5180c1 100644 --- a/docs/examples/README.md +++ b/docs/examples/README.md @@ -126,17 +126,21 @@ async function deleteRequest (port = 3001) { } ``` -## Cacheable DNS Lookup +## Production configuration -### Using CacheableLookup to cache DNS lookups in undici +### Using interceptors to add response caching, DNS lookup caching and connection retries ```js -import { Agent } from 'undici' -import CacheableLookup from 'cacheable-lookup'; +import { Agent, interceptors, setGlobalDispatcher } from 'undici' -const cacheable = new CacheableLookup(opts) +// Interceptors to add response caching, DNS caching and retrying to the dispatcher +const { cache, dns, retry } = interceptors -const agent = new Agent({ - connect: { lookup: cacheable.lookup } -}) +const defaultDispatcher = new Agent({ + connections: 100, // Limit concurrent kept-alive connections to not run out of resources + headersTimeout: 10_000, // 10 seconds; set as appropriate for the remote servers you plan to connect to + bodyTimeout: 10_000, +}).compose(cache(), dns(), retry()) + +setGlobalDispatcher(defaultDispatcher) // Add these interceptors to all `fetch` and Undici `request` calls ```