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.
By Livops team, the people who build and run LivopsUpdated
What you see in the log:
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:
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):
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:
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.1instead oflocalhost; - make the server listen on both families, or on
0.0.0.0and::; - start Node with
--dns-result-order=ipv4first[7], for example inNODE_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
[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 —
apifrom 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:
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]:
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.pemadds the PEM certificates in the file to the trusted roots, and is read only when the process starts[7].--use-system-ca, orNODE_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:
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:
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,HOSTorPORT— an address the platform knows — instead of a value you type in; the syntax is on the Variables page.URLis the service’s publichttpsaddress andHOSTandPORTare 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.appand an HTTPS certificate, with nothing to set up. - The service you call must listen on
0.0.0.0. A server app listens on0.0.0.0and the port inPORT; one that listens onlocalhostcan be reached only from inside its own container, and callers getECONNREFUSED. - 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_*andNEXT_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. - Read the cause in the logs. The Logs page, or
livops logs -fin the terminal, shows what the app printed, so log the whole error. If the app stops at start-up, the deploy fails asstart_failedand 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.
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
- undici source — lib/web/fetch/index.js (github.com). Checked .
- Node.js docs — Global objects, fetch (nodejs.org). Checked .
- Node.js docs — Errors (nodejs.org). Checked .
- undici docs — Errors (github.com). Checked .
- undici docs — Client options (github.com). Checked .
- Node.js docs — DNS (nodejs.org). Checked .
- Node.js docs — Command-line options and environment variables (nodejs.org). Checked .
- Node.js docs — Net, socket.connect options (nodejs.org). Checked .
- Node.js docs — HTTP, built-in proxy support (nodejs.org). Checked .
- undici docs — EnvHttpProxyAgent (github.com). Checked .
- Node.js docs — TLS, X509 certificate error codes (nodejs.org). Checked .
- undici source — lib/web/fetch/constants.js (bad ports) (github.com). Checked .
- undici source — lib/web/fetch/request.js (github.com). Checked .
- undici source — lib/core/connect.js (github.com). Checked .
- undici source — lib/dispatcher/client-h1.js (github.com). Checked .
Put your project online today
Connect GitHub or drop a folder. No card is asked for.
Deploy your Node.js appRelated
- ECONNREFUSED / Connection refused: why the app cannot reach its database after deployNothing was listening at the address your app tried. When the address is 127.0.0.1 or localhost, the app never read the database's real address: DATABASE_URL is not set, is not read, or is read during a build that has no database. Attach the database, read DATABASE_URL (or REDIS_URL, MYSQL_URL) at runtime, run migrations before the start rather than in the build, and keep the connection pool under the server's limit.
- Prisma P1001: Can't reach database server at … — how to fix itPrisma tried the host and port in your connection URL and nothing answered there. After a deploy that is almost always a URL that says localhost, a database that is not attached to the project, or prisma migrate deploy running in a build that has no database. Read the host in the message first: it tells you which.
- Node.js hosting in 2026: how to deploy an Express appA Node.js server in production needs one long-running process that listens on the port it is given, restarts when it crashes and exits cleanly on SIGTERM. On Livops you push a repository with package.json and it runs as a web app for 39 credits a month (39,000 so'm). Here is what Node needs, and how a VPS, Render, Railway, Fly.io, DigitalOcean and Heroku compare.
- App not listening on $PORT: why the health check failed after deployThe platform started your app, tried the port it gave it, and nothing answered in time. Almost always the app listens on its own fixed port instead of the PORT variable, listens on localhost (127.0.0.1) instead of 0.0.0.0, or crashed or was still starting when the check gave up. Listen on 0.0.0.0 and the port in PORT, and it passes.
- [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate in Python: how to fix itssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate means Python could not build a chain from the server's certificate to a root it trusts. In requests, httpx, aiohttp and urllib the usual causes are a missing or outdated CA bundle, a python.org install on macOS that never ran Install Certificates.command, a corporate proxy that re-signs HTTPS, or a server that does not send its intermediate certificate. Fix the trust store; do not turn verification off.
- import.meta.env.VITE_API_URL is undefined in production: why Vite env variables stop working after deployimport.meta.env.VITE_API_URL is undefined in production when Vite did not have the variable at the moment it built the site: Vite writes the values into the files at build time, so a variable set only where the site runs is never seen. The other usual causes: a name without the VITE_ prefix, a .env.local file that is ignored by git and never reaches the build server, a value kept in .env.development, and process.env in client code. Set the variable where the build runs, with the prefix, and build again.
- A staging environment next to productionOn Livops, Add environment on the project page makes a staging copy of your production services, each with its own address, its own variables and its own empty database, so a test never touches production data. Promote to production then ships the exact release you tested, without rebuilding. A staging environment costs half; pull request previews are billed like regular services.
- getaddrinfo ENOTFOUND in Node.js: why the host name does not resolve, and the fixError: getaddrinfo ENOTFOUND means Node asked the system for the address of a host name and got none. The name at the end of the message is the one your app really used: a typo or https:// left in a host field, the word undefined from an unset variable, a Docker Compose service name or a host that exists only on your laptop, or another platform's internal address. getaddrinfo EAI_AGAIN is a temporary DNS failure instead. Print the host, check that it resolves where the app runs, and fix the variable that holds it.