#2888·nock

15.0.0-beta.4 Doesn't support undici requests with custom agent/dispatcher

Author: lajohnstonCreated Jul 17, 2025Updated Jul 24, 2026
Labelsbugawaiting response

Please avoid duplicates

Reproducible test case

(see post)

Nock Version

15.0.0-beta.4

Node Version

v22.17.0

TypeScript Version

No response

What happened?

Hi there,

It seems the partial Undici support is working for most requests in 15.0.0-beta.4 now

One limitation we've observed though is that if you pass in a dispatcher in the request options (or use undici.setGlobalDispatcher) it results in the request not being intercepted. A custom Agent is needed to add things like certs or adjust keepAlive settings.

javascript
import { Agent, fetch } from 'undici';

const agent = new Agent({
    keepAliveTimeout: 1000,
});

const response = await fetch('some url', {
    method: 'GET',
    dispatcher: agent,
});

Note, in this example we're importing the undici library rather than using native fetch, as it seems the latter doesn't export the Undici Agent and so cannot be customised.

It seems the given dispatcher bypasses or overrides the NockAgent that's set here: https://github.com/nock/nock/blob/38628919e5d9d5ded4c4116a6e5862fb85cd3aad/lib/interceptors/undici.js#L67-L69

Workaround

Use Reflect (or some other stubbing method) when initialising the test suite to ensure undici.Agent in the code returns the Nock stub.

javascript
const undici = require('undici');

Reflect.set(undici, 'Agent', function () {
    const nockAgent = undici.getGlobalDispatcher();
    return nockAgent;
});

Would you be interested in contributing a fix?

  • yes