You can pass a dispatcher to fetch()
in Node:
import { Agent } from 'undici';
const response = await fetch(url, {
dispatcher: new Agent(/* ... */),
});
And you can set a global dispatcher if you're using undici
on its own:
import { Agent, fetch, setGlobalDispatcher } from 'undici';
setGlobalDispatcher(new Agent(/* ... */));
const response = await fetch(url);
But how would I go about obtaining the setGlobalDispatcher()
function that's bound to the global dispatcher the built-in instance of fetch()
that Node 18+ uses? Surely using a setGlobalDispatcher()
function from a version of undici
that I install will not be the same one.
According to this discussion: https://github.com/nodejs/undici/discussions/2167#discussioncomment-6239415 it can be achieved by the following:
globalThis[Symbol.for('undici.globalDispatcher.1')] = yourDispatcher;
However I agree with Mike Pomax that this isn't a great idea. A better design would be to wrap fetch
with your own local library, that overrides the dispatcher as you please. Then import that to use.