Node.js fetch ETIMEDOUT and SELF_SIGNED_CERT_IN_CHAIN Debugging
fetch failed hides everything in error.cause. Read the aggregate, trust the private CA the way curl does, route the proxy, and set the connect timeout undici does not.

Introduction & Quick Summary
Symptom. await fetch(url) rejects with TypeError: fetch failed and no other detail, while curl https://api.example.com/health returns 200 on the same host. Digging into the error object shows cause: Error: connect ETIMEDOUT 10.4.2.19:443, cause: AggregateError [ECONNREFUSED] with two addresses inside, or a TLS failure ending in self-signed certificate in certificate chain / SELF_SIGNED_CERT_IN_CHAIN. In containers behind a corporate proxy the same code works locally and fails in production.
Cause. Node's fetch is undici, and undici wraps the real network failure in error.cause, which is why the top-level message is useless. AggregateError appears because undici tries every resolved address (IPv6 and IPv4) and reports all failures together. SELF_SIGNED_CERT_IN_CHAIN is an OpenSSL verification code produced when the chain ends at a private CA — a TLS-inspecting proxy, an internal service mesh, or a self-signed dev endpoint — and Node verifies against its own bundled roots, not the operating system trust store.
Fix. Read error.cause (and its errors array) first; then align the client with what curl does: pass the private CA via NODE_EXTRA_CA_CERTS or connect.ca, route through the proxy with an undici proxy agent, set an explicit connect timeout because undici's defaults are long, and use --resolve-style overrides for hostname mismatches. Never disable TLS verification to make it pass in production.
Core Mechanics, Signatures & Reproducible Setup
A failing call and the code that surfaces the real error:
try {
const res = await fetch('https://api.internal:8443/health');
} catch (err) {
console.error(err.name, err.message); // TypeError fetch failed
const c = err.cause;
console.error(c?.code, c?.message); // SELF_SIGNED_CERT_IN_CHAIN / ETIMEDOUT
if (c instanceof AggregateError) console.error(c.errors.map((e) => [e.code, e.address]));
}The same request with an explicit dispatcher — connection timeout, private CA, and a keep-alive pool:
import { Agent, setGlobalDispatcher } from 'undici';
import { readFileSync } from 'node:fs';
const agent = new Agent({
connect: {
timeout: 5_000, // ETIMEDOUT ceiling, per address
ca: readFileSync('/etc/ssl/private/internal-ca.pem'),
},
headersTimeout: 15_000,
bodyTimeout: 30_000,
});
const res = await fetch('https://api.internal:8443/health', {
dispatcher: agent,
signal: AbortSignal.timeout(20_000), // whole-request ceiling
});Environment-wide trust, closest to what curl does with --cacert for one host:
NODE_EXTRA_CA_CERTS=/etc/ssl/private/internal-ca.pem node server.jsNODE_EXTRA_CA_CERTS appends to the bundled roots instead of replacing them, so public endpoints keep working. For a proxy, the environment variables are not honoured by a bare fetch; construct the agent:
import { EnvHttpProxyAgent, setGlobalDispatcher } from 'undici';
setGlobalDispatcher(new EnvHttpProxyAgent()); // reads HTTP_PROXY, HTTPS_PROXY, NO_PROXYKey Comparison Table
| Failure | cause.code | What actually happened | First check |
|---|---|---|---|
fetch failed | ETIMEDOUT | No answer before the connect timeout | Firewall, security group, wrong IP |
fetch failed | ECONNREFUSED (often Aggregate) | Port closed on that address | Is the service listening on 0.0.0.0? |
fetch failed | ENOTFOUND | DNS resolution failed | getent hosts, search domain |
fetch failed | SELF_SIGNED_CERT_IN_CHAIN | Private CA not trusted | Corporate proxy, internal CA |
fetch failed | CERT_HAS_EXPIRED | Cert or intermediate expired | openssl s_client -showcerts |
fetch failed | UND_ERR_CONNECT_TIMEOUT | undici's own connect timer | connect.timeout too low |
| Response 403/407 | — | Proxy or WAF rejected | Proxy agent, header auth |
| curl | fetch / undici equivalent | Notes |
|---|---|---|
--connect-timeout 5 | connect: { timeout: 5000 } | Per address, not per request |
--max-time 20 | signal: AbortSignal.timeout(20000) | Aborts the whole call |
--cacert ca.pem | connect: { ca } or NODE_EXTRA_CA_CERTS | Per-request vs process-wide |
-k | connect: { rejectUnauthorized: false } | Debug only |
-x proxy:8080 | new ProxyAgent('http://proxy:8080') | Not automatic |
--resolve host:443:1.2.3.4 | connect: { lookup } custom function | Pins the address |
-4 / -6 | autoSelectFamily: false / address family | undici tries both by default |
-v | NODE_DEBUG=undici, NODE_TLS_REJECT_UNAUTHORIZED never | Verbose diagnostics |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. AggregateError with two addresses is one real failure
undici's happy-eyeballs tries IPv6 and IPv4; both refused means the service is not listening on either, or a security group blocks both. If only ::1 fails and 127.0.0.1 succeeds, the server binds IPv4 only, and the fix belongs on the server:
// app side: listen on both families
server.listen(3000, '::');2. Private CA: three levels of fix
Pick by blast radius. One host: pass connect.ca in the dispatcher. Whole service: NODE_EXTRA_CA_CERTS. Bundled environment where Node must follow the OS store: node --use-openssl-ca, which switches to the system store and stops using the bundled roots.
# inspect what the server actually presents, including the chain
openssl s_client -connect api.internal:8443 -servername api.internal -showcerts </dev/null 2>/dev/null | openssl x509 -noout -subject -issuer -datesIf the issuer is your proxy's CA, the certificate is generated per host by the proxy; trusting it is the correct action for a managed network and the wrong action on a laptop outside it.
3. A hostname that does not match the certificate
Internal services are frequently reached by IP or by a name the certificate does not carry. fetch verifies both chain and name, so it fails where curl --resolve succeeded with a different name. The undici equivalent pins the address while keeping the Host and SNI:
import dns from 'node:dns';
const agent = new Agent({
connect: {
servername: 'api.internal',
lookup(hostname, opts, cb) {
if (hostname === 'api.internal') return cb(null, [{ address: '10.4.2.19', family: 4 }]);
return dns.lookup(hostname, opts, cb);
},
},
});4. Timeouts that never fire
undici's defaults are generous (300 s for headers and body), so a half-open connection hangs a worker for minutes. ETIMEDOUT in cause is the OS-level failure; UND_ERR_CONNECT_TIMEOUT is undici's own timer. Set both layers, and make retries idempotent:
async function get(url, tries = 3) {
for (let i = 0; i < tries; i++) {
try {
return await fetch(url, { dispatcher: agent, signal: AbortSignal.timeout(10_000) });
} catch (e) {
if (i === tries - 1 || e.cause?.code === 'ENOTFOUND') throw e;
await new Promise((r) => setTimeout(r, 200 * 2 ** i));
}
}
}5. Proxy variables that curl reads and fetch ignores
HTTPS_PROXY, NO_PROXY and ALL_PROXY are curl conventions. A bare fetch connects directly, which in a locked-down network ends as ETIMEDOUT on the proxy's address or on the target's. EnvHttpProxyAgent implements the same convention, including NO_PROXY matching, but only if the environment is set before the agent is constructed.
6. Requests that "work" but return HTML from a proxy
A TLS-inspecting proxy can return a 200 with a login page, so res.ok is true and res.json() throws Unexpected token '<'. Log the content type and the first bytes when a response shape is unexpected; the JSON formatter shows immediately that the body is not JSON.
Common Compilation/Runtime Mistakes & Version Gotchas
NODE_TLS_REJECT_UNAUTHORIZED=0. Disables verification process-wide, including for database clients and outbound webhooks. It is the most common "fix" in issue threads and the wrong one outside a throwaway container.- Node 18 vs 20+ fetch. In Node 18,
fetchis experimental and prints a warning; the bundled undici is older, andEnvHttpProxyAgentdoes not exist before undici 6.13. Upgrade rather than patch around missing agents. - Reading
err.messageonly. Every undici network failure saysfetch failed; the information is inerr.cause, anderr.cause.errorsfor aggregates. fetchdoes not reject on 4xx/5xx. A 502 from a proxy looks like success unless you checkres.ok; wrap and throw explicitly.- Keep-alive reuse after a proxy restart. A pooled socket to a dead upstream surfaces as a reset on the next request. Retry once on
ECONNRESET, or set a shortkeepAliveTimeout. --use-openssl-cain containers. The slim images often ship no CA bundle; switching to the system store then fails every public request. Installca-certificatesfirst.- HTTP/2 and
--http1.1. Some proxies and internal gateways break on HTTP/2 upgrades; undici negotiates over ALPN by default, andallowH2: false(or connecting to an HTTP/1.1 endpoint) resolves it.
Related tools. Translate a working curl invocation into the flags and headers your client needs with the cURL builder, split a target URL into host, port and query parts with the URL parser, and base64-encode a proxy credential for a Proxy-Authorization header with the base64 encoder instead of pasting the raw secret into a config file.
Try matching browser tools
All toolsSmall utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Node.js guides
All Node.js guidesERR_REQUIRE_ESM and __dirname Is Not Defined in ESM Projects
require of an ESM-only package has nothing to load, and ESM creates none of the CommonJS wrapper globals. Dynamic import, createRequire, and the path replacements.
Node.js JavaScript heap out of memory: Snapshots and Real Leaks
Distinguish needs more from leaks before raising the flag: external memory and heap tell different stories, and a heap ceiling at three quarters of the container limit keeps V8 able to report.
Node.js EventEmitter: once, error Events, and Listener Memory Leaks
emit is synchronous, so a throwing listener aborts the rest. An error event with no listener crashes the process, and a listener per request is the classic leak.
Node.js fs/promises: Read, Write, Watch, and Atomic File Operations
writeFile truncates before writing, so a crash leaves half a file. The atomic pattern is temp file, fsync, rename; readFile loads everything, so large files need streams.
More in Node.js
All Node.js guidesThe guides filed next to this one in Node.js, in library order.