3

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.

radostin04
  • 31
  • 3
  • https://github.com/nodejs/undici/issues/1531#issuecomment-1178869993 But check some of the other causes in the thread. – Dave Newton Jul 24 '23 at 15:33
  • I did find that issue, but as far as I can tell there is no way to import setGlobalDispatcher when using the fetch api built into nodejs? Please correct me if I'm wrong, but i get an error when i try to import things from undici as the issue shows – radostin04 Jul 24 '23 at 16:34

1 Answers1

1

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?