Digiaru

Digiaru started this conversation 1 week ago.

Node.js fetch error: TypeError: fetch failed or UND_ERR_CONNECT_TIMEOUT

When using built-in fetch() in Node.js (v18+), requests occasionally fail with: php Copy code TypeError: fetch failed cause: ConnectTimeoutError (code: 'UND_ERR_CONNECT_TIMEOUT') Even using AbortSignal.timeout(…) set to a high value (e.g. 20 s) doesn't prevent the error. How can I reliably make requests with longer connect timeouts?

Kar

Posted 1 week ago

Node’s fetch() is implemented using the Undici library under the hood. It imposes a fixed 10 s socket connect timeout that cannot be overridden using AbortSignal.timeout() alone. Thus longer timeouts still result in UND_ERR_CONNECT_TIMEOUT after 10 seconds GitHub+4GitHub+4GitHub+4. 🛠️ Fix Options:

  1. Use a custom Undici agent to extend connectTimeout: js Copy code import { fetch, setGlobalDispatcher, Agent } from 'undici'; setGlobalDispatcher(new Agent({ connect: { timeout: 20000 } })); // 20 s const response = await fetch(url); This overrides the default 10 s connect timeout Stack OverflowGitHub.
  2. Combine with AbortSignal.timeout() for response or header-level timeouts: js Copy code await fetch(url, { signal: AbortSignal.timeout(30_000) });
  3. Prefer using node-fetch, axios, or other clients if precise control is needed. ✅ Best Practices: • Always wrap fetch in try/catch. • Monitor and retry on ConnectTimeoutError. • In unreliable networks, consider increasing DNS resolution timeout via: bash Copy code export NODE_OPTIONS="--network-family-autoselection-attempt-timeout=500" to avoid ETIMEDOUT on IPv6 resolution GitHubGitHubGitHub.