Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readNode.js
#Node.js#fetch#TLS#Networking
3D illustration of a request packet stopped at a TLS padlock gate with a broken certificate ribbon and a curl terminal beside it

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:

js
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:

js
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:

bash
NODE_EXTRA_CA_CERTS=/etc/ssl/private/internal-ca.pem node server.js

NODE_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:

js
import { EnvHttpProxyAgent, setGlobalDispatcher } from 'undici'; setGlobalDispatcher(new EnvHttpProxyAgent()); // reads HTTP_PROXY, HTTPS_PROXY, NO_PROXY

Key Comparison Table

Failurecause.codeWhat actually happenedFirst check
fetch failedETIMEDOUTNo answer before the connect timeoutFirewall, security group, wrong IP
fetch failedECONNREFUSED (often Aggregate)Port closed on that addressIs the service listening on 0.0.0.0?
fetch failedENOTFOUNDDNS resolution failedgetent hosts, search domain
fetch failedSELF_SIGNED_CERT_IN_CHAINPrivate CA not trustedCorporate proxy, internal CA
fetch failedCERT_HAS_EXPIREDCert or intermediate expiredopenssl s_client -showcerts
fetch failedUND_ERR_CONNECT_TIMEOUTundici's own connect timerconnect.timeout too low
Response 403/407—Proxy or WAF rejectedProxy agent, header auth
curlfetch / undici equivalentNotes
--connect-timeout 5connect: { timeout: 5000 }Per address, not per request
--max-time 20signal: AbortSignal.timeout(20000)Aborts the whole call
--cacert ca.pemconnect: { ca } or NODE_EXTRA_CA_CERTSPer-request vs process-wide
-kconnect: { rejectUnauthorized: false }Debug only
-x proxy:8080new ProxyAgent('http://proxy:8080')Not automatic
--resolve host:443:1.2.3.4connect: { lookup } custom functionPins the address
-4 / -6autoSelectFamily: false / address familyundici tries both by default
-vNODE_DEBUG=undici, NODE_TLS_REJECT_UNAUTHORIZED neverVerbose 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:

js
// 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.

bash
# 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 -dates

If 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:

js
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:

js
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, fetch is experimental and prints a warning; the bundled undici is older, and EnvHttpProxyAgent does not exist before undici 6.13. Upgrade rather than patch around missing agents.
  • Reading err.message only. Every undici network failure says fetch failed; the information is in err.cause, and err.cause.errors for aggregates.
  • fetch does not reject on 4xx/5xx. A 502 from a proxy looks like success unless you check res.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 short keepAliveTimeout.
  • --use-openssl-ca in containers. The slim images often ship no CA bundle; switching to the system store then fails every public request. Install ca-certificates first.
  • HTTP/2 and --http1.1. Some proxies and internal gateways break on HTTP/2 upgrades; undici negotiates over ALPN by default, and allowH2: 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 tools

Small utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Node.js guides

More in Node.js

All Node.js guides

The guides filed next to this one in Node.js, in library order.