I am using the Fetch API introduced in NodeJS 18 to access an API. However, the request always times out after 10 seconds with the following error message.
TypeError: fetch failed
at Object.fetch (node:internal/deps/undici/undici:11576:11)
at processTicksAndRejections (node:internal/process/task_queues:95:5) {
cause: ConnectTimeoutError: Connect Timeout Error
at onConnectTimeout (node:internal/deps/undici/undici:8522:28)
at node:internal/deps/undici/undici:8480:50
at Immediate._onImmediate (node:internal/deps/undici/undici:8509:37)
at processImmediate (node:internal/timers:478:21) {
code: 'UND_ERR_CONNECT_TIMEOUT'
}
}
I want to INCREASE the time before the fetch request times out, however I have not been able to find way to do this with the built-in NodeJS API.
Adding to Istiaq's answer, you don't need to set the timeout on the global level. A dispatcher can be applied as an option to the fetch call.
import { Agent } from "undici";
await fetch("https://example.com", {
dispatcher: new Agent({ connectTimeout: 300 })
});
https://undici.nodejs.org/#/?id=undicifetchinput-init-promise
I faced the same problem using Node 18 and fetch api, and I was able to increase the connect timeout as shown in https://github.com/nodejs/undici/issues/1531#issuecomment-1178869993 I had to add undici using npm:
npm install undici
Then I was able to import setGlobalDispatcher, fetch and Agent from undici:
import { fetch, setGlobalDispatcher, Agent} from 'undici';
And then I used the setGlobalDispatcher globally at the top of the module before any function as follows:
setGlobalDispatcher(new Agent({connect: { timeout: 20_000 }}));
After this it all worked and the 10s connect timeout was correctly increased to 20s.
Please note that in my case i also used an updated "fetchWithTimeout" method instead of just plain fetch to cater for request timeouts. If you also need to handle request timeout, you can find a few implementations here at Fetch API request timeout?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With