# TypeError: fetch failed in Node.js: read the cause, then fix it

> fetch failed is only the wrapper. Node's fetch puts the real network error in err.cause: ECONNREFUSED when nothing listens at that address, ENOTFOUND when the name does not resolve, a connect or headers timeout, a certificate error, or a proxy the request never used. Print the cause first; after a deploy it is most often a URL that still says localhost or a service address that was never set.

Source: https://livops.dev/en/guides/error-node-fetch-failed

By Livops team, the people who build and run Livops. Updated 3 December 2026.

What you see in the log:

```text
TypeError: fetch failed
```

and often nothing else, because the code logged `err.message`. Node's `fetch()` is built on undici[2], and when a request fails as a network error, undici rejects with `new TypeError('fetch failed', { cause })`[1]: the message is always the same, and the real error is in `err.cause`. This page shows how to print that cause, what each one means, how to fix it in a deployed app, and how services find each other on Livops.

## What does fetch failed mean?

The request never got an HTTP response. undici rejects with `fetch failed` only when the response is a network error[1]; a `404` or a `500` is a response, so it resolves the promise and never shows up as this error.

Two near misses are different errors. A URL that cannot be parsed, such as `undefined/users` from a variable that is not set, throws `TypeError: Failed to parse URL from undefined/users`[13]. A request cancelled through its `signal`, for example `AbortSignal.timeout(5000)`[2], rejects with the signal's reason[1] — a `TimeoutError` — not with `fetch failed`.

## Print the cause first

`error.cause` holds the underlying error, and `util.inspect()` prints it recursively[3], so `console.error(err)` shows it and `console.error(err.message)` does not:

```js
try {
  const res = await fetch(url)
} catch (err) {
  console.error(err)                  // prints the [cause] block
  const c = err.cause
  console.error(c?.code, c?.address, c?.port, c?.message)
  for (const e of c?.errors ?? []) {  // AggregateError: one per address tried
    console.error(' ', e.code, e.address, e.port)
  }
  throw err
}
```

A refused connection prints like this (stack lines removed):

```text
TypeError: fetch failed
  [cause]: Error: connect ECONNREFUSED 127.0.0.1:3000
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 3000
  }
}
```

A system error carries `code`, `syscall`, and, for a network failure, the `address` and `port` that failed[3]. Read those two first: they say where the request really went.

| `err.cause` | What it means |
| --- | --- |
| `ECONNREFUSED` | The host answered, nothing was listening on that port[3] |
| `ENOTFOUND` | The host name did not resolve, or the lookup failed in another way[6] |
| `ETIMEDOUT` | The other side did not respond in time[3] |
| `ECONNRESET` | The other side closed the connection forcibly[3] |
| `UND_ERR_CONNECT_TIMEOUT` | No connection within undici's `connectTimeout`, 10 seconds by default[4][5] |
| `UND_ERR_HEADERS_TIMEOUT` | Connected, but the response headers did not arrive within `headersTimeout`, 300 seconds by default[4][5] |
| `UND_ERR_SOCKET` | An error on the socket, such as `other side closed`[4][15] |
| `SELF_SIGNED_CERT_IN_CHAIN`, `UNABLE_TO_VERIFY_LEAF_SIGNATURE`, `CERT_HAS_EXPIRED` | The server's certificate was not accepted[11] |
| `ERR_TLS_CERT_ALTNAME_INVALID` | The host name is not one the certificate was issued for[3] |
| `AggregateError` | Several addresses were tried and each failed; `cause.errors` has one error per address[8] |
| `bad port` | fetch refused the port itself[1][12] |

## Causes, most common first

### 1. The URL says localhost

The code calls `http://localhost:4000/api`, which works on your laptop because the API runs there too. After a deploy each service runs in its own container, so `localhost` is the caller's own container, nothing listens on that port, and the cause is `ECONNREFUSED 127.0.0.1:4000`. The same happens when server-side code fetches its own API while the app is being built: no server of yours is running yet.

The fix is to call the other service by its real address, read from a variable, and to stop at start-up when the variable is missing rather than quietly trying localhost:

```js
const API_URL = process.env.API_URL
if (!API_URL) throw new Error('API_URL is not set')

const res = await fetch(new URL('/users', API_URL))
```

During a build, call the function behind the endpoint directly, or move the request to request time.

### 2. localhost resolved to ::1

If the cause says `connect ECONNREFUSED ::1:3000`, or is an `AggregateError [ECONNREFUSED]`, the name resolved to IPv6 first. Since Node 17, `dns.lookup()` returns addresses in the order the resolver gives them, `verbatim`, rather than IPv4 first[6][7], and `localhost` often resolves to `::1`. A server that listens only on `127.0.0.1` refuses it. With `autoSelectFamily`, on by default in `node:net`, Node tries the IPv6 and IPv4 addresses in turn[8], and when every one fails the cause is an `AggregateError` with each attempt in `cause.errors`.

Any of these fixes it:

- call `127.0.0.1` instead of `localhost`;
- make the server listen on both families, or on `0.0.0.0` and `::`;
- start Node with `--dns-result-order=ipv4first`[7], for example in `NODE_OPTIONS`.

The same ordering matters for remote hosts: a name that has an IPv6 address, called from a network without an IPv6 route, can time out on that address before IPv4 is tried.

### 3. The service address is not set

The variable holding the other service's URL is empty, has a different name in the code (`API_URL` in one place, `BACKEND_URL` in another), or lives in a `.env` file that never reached the server. Without a fallback this is `Failed to parse URL from undefined/...`[13]; with a fallback to localhost it is cause 1. Set the variable on the platform under the name the code reads, and restart the process: variables are read when it starts.

Browser code is different again: bundler variables such as `VITE_*` or `NEXT_PUBLIC_*` are copied into the files at build time, so they have to be set before the build.

### 4. The name does not resolve: ENOTFOUND

```text
[cause]: Error: getaddrinfo ENOTFOUND api.internal
```

undici opens its connections with `node:net`[14], whose default lookup is `dns.lookup()`[8], and that asks the operating system, resolving a name the same way `ping` does[6]. `ENOTFOUND` is set not only when the name does not exist but also when the lookup fails in other ways[6]. After a deploy it usually means:

- a typo in the host, or a scheme pasted into it (`https://https://api...`);
- an internal name from somewhere else — `api` from a Docker Compose file, or a host that exists only on another platform's private network;
- a name that exists only in another environment, such as a staging host called from production.

Check the name from where the app runs, as below. If it does not resolve there, fix the address; nothing in the code will make it resolve.

### 5. A timeout

`UND_ERR_CONNECT_TIMEOUT` means no TCP connection within `connectTimeout`, 10 seconds by default[5]. Recent undici versions name the address in the message: `Connect Timeout Error (attempted address: host:port, timeout: 10000ms)`[14], and when several addresses timed out, the original `AggregateError` stays in its `cause`[4]. Usually a firewall drops the packets, or the host is on a private network the app is not on. Find out whether the host is reachable from where the app runs before raising any timeout.

`UND_ERR_HEADERS_TIMEOUT` means the connection was made and the server did not send its headers within `headersTimeout`, 300 seconds by default[5]. The other service is slow or stuck; its logs say why. To fail sooner than five minutes, give the request your own deadline:

```js
const res = await fetch(url, { signal: AbortSignal.timeout(10_000) })
```

which rejects with a `TimeoutError` instead of `fetch failed`[1][2].

### 6. A proxy is needed, or is in the way

Node uses `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` for `fetch` only when `NODE_USE_ENV_PROXY=1` is set or Node is started with `--use-env-proxy`, available from Node 24.0 and 22.21[7]. `http.setGlobalProxyFromEnv()` turns the same support on for `fetch()` at run time, from Node 25.4 and 24.14[9]. On older versions, install undici and make its `EnvHttpProxyAgent`, which reads the same variables[10], the global dispatcher; Node's `fetch` uses it too[2]:

```js
import { setGlobalDispatcher, EnvHttpProxyAgent } from 'undici'
setGlobalDispatcher(new EnvHttpProxyAgent())
```

The opposite failure: a proxy is set, and requests to internal hosts go to the proxy, which cannot reach them. List those hosts in `NO_PROXY`, a comma-separated list of hosts that bypass the proxy[9].

### 7. The certificate is not accepted

The cause has a certificate code such as `SELF_SIGNED_CERT_IN_CHAIN`, `UNABLE_TO_GET_ISSUER_CERT_LOCALLY`, `UNABLE_TO_VERIFY_LEAF_SIGNATURE` or `CERT_HAS_EXPIRED`[11]. For the first three, Node adds a hint to try `--use-system-ca` if the root CA is installed locally[11].

- **An internal service signed by your own CA**, or a corporate proxy that re-signs traffic: give Node that CA. `NODE_EXTRA_CA_CERTS=/path/ca.pem` adds the PEM certificates in the file to the trusted roots, and is read only when the process starts[7]. `--use-system-ca`, or `NODE_USE_SYSTEM_CA=1`, also trusts the system's certificate store[7].
- **`CERT_HAS_EXPIRED`**: the server's certificate has expired[11]. Renew it there; nothing on the client side is a fix.
- **`ERR_TLS_CERT_ALTNAME_INVALID`**: the host name or IP you called is not in the certificate's subjectAltNames[3]. Call the service by the name on its certificate, not by IP.

Do not set `NODE_TLS_REJECT_UNAUTHORIZED=0`: it disables certificate validation for all TLS connections, and Node's docs strongly discourage it[7].

### 8. The other side closed the connection

`SocketError: other side closed`[15] (`UND_ERR_SOCKET`[4]) or `ECONNRESET`[3]: the connection was open and the server closed it. Either the server crashed or restarted mid-request — its logs show it — or it closed an idle kept-alive connection just as the client reused it. undici keeps idle sockets for 4 seconds by default, unless the server's keep-alive hints say otherwise[5]. Retrying an idempotent request (`GET`, `PUT`) once covers the second case.

### 9. A blocked port

The cause is `Error: bad port`. Following the Fetch standard, undici refuses a list of ports[1][12], among them `6000`, `6665` to `6669`, `5060`, `10080` and `25`[12]. A service on one of those cannot be called with `fetch`; move it to another port.

## How to confirm the fix

Run the request from where the app runs, with the same variables, and print the cause:

```sh
node -e 'fetch(process.env.API_URL).then(r => console.log(r.status), e => console.error(e.cause ?? e))'
```

A status, even `404`, means the network is fine and `fetch failed` is gone. To check the name alone:

```sh
node -e 'require("node:dns").lookup(process.argv[1], { all: true }, console.log)' api.example.com
```

`{ all: true }` returns every address with its family, 4 or 6[6]; an IPv6 address first explains cause 2. `process.versions.undici` tells you which undici your Node bundles[2], which matters when comparing error messages.

## On Livops

- **Call a service by its address, from a variable.** In the service's **Variables**, a value can be a reference to another service's `URL`, `HOST` or `PORT` — an address the platform knows — instead of a value you type in; the syntax is on the [Variables](https://livops.dev/en/docs/variables) page. `URL` is the service's public `https` address and `HOST` and `PORT` are where it answers on the environment's internal network. References work only within their own environment, so a staging service points at staging.
- **Every service has HTTPS.** Each one gets an address like `<name>.livops.app` and an HTTPS certificate, with nothing to set up.
- **The service you call must listen on `0.0.0.0`.** A server app listens on `0.0.0.0` and the port in `PORT`; one that listens on `localhost` can be reached only from inside its own container, and callers get `ECONNREFUSED`.
- **Variables take effect on the next deploy.** After adding or changing one, deploy again, or restart the service to apply it now.
- **Browser code gets its variables at build time.** A static site's `VITE_*` and `NEXT_PUBLIC_*` values are written into the files during the build and are visible to anyone, so an API address for browser code is set before the build, and no secret goes there.
- **Databases are not HTTP, but the same rule holds.** A database's host is an internal name such as `postgres`, with no public port; the same failure with a database driver is covered in [ECONNREFUSED: the app cannot reach its database](https://livops.dev/en/guides/error-econnrefused-database).
- **Read the cause in the logs.** The **Logs** page, or `livops logs -f` in the terminal, shows what the app printed, so log the whole error. If the app stops at start-up, the deploy fails as `start_failed` and a web app's previous version keeps serving.

A web app costs **39 credits a month**, a worker **19**. Missing variables at start-up are covered in [The app did not start](https://livops.dev/en/docs/error-start#app-env).

## Questions

**What does TypeError fetch failed mean in Node.js?**

That the request failed before any HTTP response arrived: the connection was refused, the name did not resolve, the connection timed out, or TLS failed. Node's fetch, built on undici, wraps that network error in a TypeError with the message fetch failed and keeps the original in err.cause.

**How do I see the real error behind fetch failed?**

Log the error object itself, console.error(err), or log err.cause. Node prints the cause under a [cause] line with its code, address and port. Logging only err.message, or the error inside a template string, prints fetch failed and nothing else.

**Does a 404 or 500 response cause fetch failed?**

No. A 404 or a 500 is an HTTP response, and fetch resolves with it; check res.ok or res.status. fetch failed means no response arrived at all.

**Why does fetch to localhost work on my machine but fail after deploy?**

On your machine the other service runs on the same computer. After a deploy each service runs in its own container, where localhost is the container itself and nothing else listens there. Call the other service by the address your platform gives it, read from a variable.

**Why does the cause say ECONNREFUSED ::1?**

Since Node 17, localhost is used in the order the resolver returns it, and that is often the IPv6 address ::1 first. A server that listens only on 127.0.0.1 refuses ::1. Call 127.0.0.1 directly, make the server listen on both, or start Node with --dns-result-order=ipv4first.

**Is it safe to set NODE_TLS_REJECT_UNAUTHORIZED=0 to fix a certificate error?**

No. It turns off certificate validation for every TLS connection the process makes, and Node's docs strongly discourage it. Add the missing CA with NODE_EXTRA_CA_CERTS or --use-system-ca, or fix the certificate on the server.

**Does Node's fetch use HTTP_PROXY and HTTPS_PROXY?**

Only when you ask it to: set NODE_USE_ENV_PROXY=1 or start Node with --use-env-proxy, on Node 24 or 22.21 and later. On older versions, install undici and set an EnvHttpProxyAgent as the global dispatcher.

## Sources

1. [undici source — lib/web/fetch/index.js](https://github.com/nodejs/undici/blob/main/lib/web/fetch/index.js). Checked 3 December 2026.
2. [Node.js docs — Global objects, fetch](https://nodejs.org/api/globals.html). Checked 3 December 2026.
3. [Node.js docs — Errors](https://nodejs.org/api/errors.html). Checked 3 December 2026.
4. [undici docs — Errors](https://github.com/nodejs/undici/blob/main/docs/docs/api/Errors.md). Checked 3 December 2026.
5. [undici docs — Client options](https://github.com/nodejs/undici/blob/main/docs/docs/api/Client.md). Checked 3 December 2026.
6. [Node.js docs — DNS](https://nodejs.org/api/dns.html). Checked 3 December 2026.
7. [Node.js docs — Command-line options and environment variables](https://nodejs.org/api/cli.html). Checked 3 December 2026.
8. [Node.js docs — Net, socket.connect options](https://nodejs.org/api/net.html). Checked 3 December 2026.
9. [Node.js docs — HTTP, built-in proxy support](https://nodejs.org/api/http.html). Checked 3 December 2026.
10. [undici docs — EnvHttpProxyAgent](https://github.com/nodejs/undici/blob/main/docs/docs/api/EnvHttpProxyAgent.md). Checked 3 December 2026.
11. [Node.js docs — TLS, X509 certificate error codes](https://nodejs.org/api/tls.html). Checked 3 December 2026.
12. [undici source — lib/web/fetch/constants.js (bad ports)](https://github.com/nodejs/undici/blob/main/lib/web/fetch/constants.js). Checked 3 December 2026.
13. [undici source — lib/web/fetch/request.js](https://github.com/nodejs/undici/blob/main/lib/web/fetch/request.js). Checked 3 December 2026.
14. [undici source — lib/core/connect.js](https://github.com/nodejs/undici/blob/main/lib/core/connect.js). Checked 3 December 2026.
15. [undici source — lib/dispatcher/client-h1.js](https://github.com/nodejs/undici/blob/main/lib/dispatcher/client-h1.js). Checked 3 December 2026.
