# TypeError: fetch failed (Node.js)

Thrown by Node's built-in fetch (undici) when no response arrived at all: a DNS, TCP, TLS or socket failure. The message is always those two words; the specific failure sits in the error's cause property, which many loggers drop.

```
TypeError: fetch failed
    at node:internal/deps/undici/undici:13510:13
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async getUser (/app/src/api.js:8:15) {
  [cause]: Error: getaddrinfo ENOTFOUND api.internal.example
      at GetAddrInfoReqWrap.onlookupall [as oncomplete] (node:dns:120:26) {
    errno: -3008,
    code: 'ENOTFOUND',
    syscall: 'getaddrinfo',
    hostname: 'api.internal.example'
  }
}
```

## Quick fix

Print err.cause, not just err.message: it holds the real failure, such as ENOTFOUND, ECONNREFUSED, UND_ERR_CONNECT_TIMEOUT or a certificate error. Fix that underlying problem (hostname, port, firewall, proxy, CA bundle), and make your logger serialize the cause chain so the next occurrence explains itself.

1. Catch the error and log err.cause and err.cause.code along with the URL.
2. ENOTFOUND or EAI_AGAIN: fix the hostname or DNS inside that environment.
3. ECONNREFUSED: start the target service or correct the port.
4. UND_ERR_CONNECT_TIMEOUT: check firewalls, security groups and egress rules.
5. Certificate errors: add your internal CA with NODE_EXTRA_CA_CERTS.
6. Behind an HTTP proxy, route fetch through undici's EnvHttpProxyAgent or ProxyAgent.

```ts
try {
  const res = await fetch(url);
  // ...
} catch (err) {
  const cause = (err as Error & { cause?: { code?: string; message?: string } }).cause;
  console.error('fetch failed', {
    url,
    code: cause?.code,
    reason: cause?.message ?? String(cause),
  });
  throw err;
}
```

## Why it happens

### DNS lookup failed (ENOTFOUND, EAI_AGAIN)

A typo in the hostname, an internal name that only resolves inside a VPC or cluster, or a container without working DNS. EAI_AGAIN means the resolver itself timed out or could not be reached, which is often transient.

### Connection refused (ECONNREFUSED)

Nothing listens on that host and port. On Node before 18.18 or 20, a common local twist is localhost resolving to ::1 while the target server binds only 127.0.0.1.

### Connect timeout (UND_ERR_CONNECT_TIMEOUT)

undici gives up on the TCP handshake after 10 seconds by default. Firewalls and security groups that silently drop packets produce a timeout rather than a refusal, so this cause points at network policy.

### TLS verification failed

Self-signed certificates, private CAs and corporate TLS inspection show up as DEPTH_ZERO_SELF_SIGNED_CERT, SELF_SIGNED_CERT_IN_CHAIN or UNABLE_TO_VERIFY_LEAF_SIGNATURE in the cause. An expired certificate on the server shows CERT_HAS_EXPIRED instead.

### Socket closed by the other side (UND_ERR_SOCKET)

The server or a proxy closed a pooled keep-alive connection that undici reused. Appears after idle periods when the upstream's keep-alive timeout is shorter than the client's.

## Other fixes

- Point NODE_EXTRA_CA_CERTS at a PEM file containing your internal CA instead of disabling TLS verification.
- Use 127.0.0.1 instead of localhost when the local server listens on IPv4 only.
- Retry idempotent requests once when the cause is UND_ERR_SOCKET or ECONNRESET.
- Raise undici's connect timeout with a custom Agent only after confirming the network path is slow rather than blocked.

## Same error, other wording

- `TypeError: fetch failed [cause]: Error: getaddrinfo ENOTFOUND`
- `TypeError: fetch failed [cause]: ConnectTimeoutError: Connect Timeout Error`
- `TypeError: fetch failed [cause]: SocketError: other side closed`
- `TypeError: Failed to fetch`

## Sources

- [Node.js globals: fetch](https://nodejs.org/api/globals.html)
- [Node.js CLI: NODE_EXTRA_CA_CERTS](https://nodejs.org/api/cli.html)
- [MDN: Error.prototype.cause](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause)

---

To see this error the next time it happens in production, with the stack trace and the steps before it: Runheed records it and serves it to your coding agent over MCP. Setup instructions an agent can follow: https://runheed.com/SETUP.txt

Human-readable version: https://runheed.com/errors/fetch-failed
