Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Setting or raising the timeout of Node.js built-in fetch

ErrorTypeError: fetch failed

Short answer

Built-in fetch has no timeout option. Waiting limits come from undici, the library under it: 10 s to connect, and 300 s each for headers and body. Check the error code to see which one fired. Raise it with an undici Agent, or cap a single call with AbortSignal.timeout().

  • Applies to Node.js 22, Node.js 24, undici 7
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    fetch failed is a wrapper. Log the error together with its cause, and read the UND_ERR code to learn which timeout fired.

    try {
      await fetch(url);
    } catch (err) {
      console.error(err, err.cause);
    }
  2. 2Match what you see, then jump to its fix

    1. 1UND_ERR_HEADERS_TIMEOUT: the full response headers were not received before the headers timeout elapsed.The server took longer than 300 seconds to send the response headersFix
    2. 2UND_ERR_BODY_TIMEOUT while reading res.json(), res.text() or a stream.The body stalled: no data arrived for 300 secondsFix
    3. 3UND_ERR_CONNECT_TIMEOUT: a connection could not be established before the connection timeout elapsed.The connection was not established within 10 secondsFix
    4. 4Requests hang for minutes because the defaults are long.You want a shorter limit than the defaultsFix

What does the error look like?

  • TypeError: fetch failed
  • UND_ERR_CONNECT_TIMEOUT
  • UND_ERR_HEADERS_TIMEOUT
  • UND_ERR_BODY_TIMEOUT

Cause 1 of 4

The server took longer than 300 seconds to send the response headers

1Check

The undici default for headersTimeout is 300000 ms. A slow report, an export or a cold serverless function can pass it.

curl -o /dev/null -s -w 'time to first byte: %{time_starttransfer}s\n' https://api.example.com/slow-report

2Fix

Install undici, make an Agent with a higher headersTimeout, and pass it as the dispatcher of fetch. Use the fetch from the same package, because mixing versions can behave differently.

// npm install undici
import { fetch, Agent } from 'undici';

const agent = new Agent({ headersTimeout: 600_000, bodyTimeout: 600_000 });
const res = await fetch('https://api.example.com/slow-report', { dispatcher: agent });

3Verify

The slow call now completes, or fails only after the new limit.

node slow-call.mjs

Confirmed by github.com

Did this fix it?

Cause 2 of 4

The body stalled: no data arrived for 300 seconds

1Check

bodyTimeout limits the gap between two chunks, not the whole download. A server that stops sending mid-stream trips it. 0 disables it.

curl -N -s https://api.example.com/stream | head -c 200

2Fix

If the stream is slow but alive (long polling, server-sent events), raise bodyTimeout on the Agent. If the server is hanging, fix the server instead.

import { Agent, setGlobalDispatcher } from 'undici';
setGlobalDispatcher(new Agent({ bodyTimeout: 0 }));

3Verify

The stream stays open as long as the server keeps sending.

node stream-client.mjs

Confirmed by github.com

Did this fix it?

Cause 3 of 4

The connection was not established within 10 seconds

1Check

Check that the host answers at all, from the same machine or container. Packet drops by a firewall look exactly like this.

curl -v --connect-timeout 5 https://api.example.com/

2Fix

If the host is reachable but slow (a far region, a VPN), raise connectTimeout on the Agent. If curl also hangs, fix the network path, because a longer timeout only delays the error.

import { Agent, setGlobalDispatcher } from 'undici';
setGlobalDispatcher(new Agent({ connectTimeout: 30_000 }));

3Verify

The request connects, or still fails with a clear network error.

curl -v --connect-timeout 5 https://api.example.com/

Confirmed by github.com

Did this fix it?

Cause 4 of 4

You want a shorter limit than the defaults

1Check

Decide how long one call may take in total. AbortSignal.timeout() counts from the moment you create it.

grep -rn "fetch(" src/ | head

2Fix

Pass a timeout signal to fetch. When it fires, the promise rejects with a TimeoutError, which you can tell apart from a network failure.

try {
  const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
  console.log(res.status);
} catch (err) {
  if (err.name === 'TimeoutError') console.error('took longer than 5 s');
  else throw err;
}

3Verify

Point the call at a slow endpoint and confirm it fails after 5 seconds.

node slow-test.mjs

Confirmed by developer.mozilla.org

Did this fix it?

How do I stop it coming back?

  • Give every outbound call an explicit signal, so a stuck dependency cannot hold a request for 5 minutes.
  • Keep the Agent in one shared module, so every call uses the same limits.
  • Log err.cause for failed fetches. The bare 'fetch failed' hides the real reason.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Back end

ng serve says it cannot determine the project or target

Cannot determine project for command.

The Angular CLI looked through angular.json for a project that defines the target you asked for (serve, build, test) and found none, or found several and could not pick one.

3 causes, each with a fix

Back end

ng serve cannot find the dev-server builder package

Could not find the implementation for builder @angular/build:dev-server

The builder named in angular.json (for example @angular-devkit/build-angular:dev-server) is looked up as an npm package starting from the workspace root.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.