Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Next.js: TypeError fetch failed in a Server Component

fetch failed hides the transport error in error.cause. Read the code, then fix DNS, refused connections, build-time fetches, TLS trust, or a missing proxy.

~5 min readNext.js
#nextjs#fetch#server-components#undici
Bold white headline reading FETCH FAILED with a Next.js server crate passing a broken request card on the right.

Introduction & Quick Summary

A Server Component or route handler fails with a message that says nothing useful:

code
TypeError: fetch failed at async getPosts (./src/lib/api.ts:12:18) at async Page (./app/posts/page.tsx:8:9) [cause]: Error: getaddrinfo ENOTFOUND api.internal at GetAddrInfoReqWrap.onlookupall (node:dns:120:26)

fetch failed is the wrapper. The transport error — DNS failure, refused connection, TLS rejection, reset socket — is in error.cause, and the cause is the only part that tells you what to fix. Code that catches the TypeError and logs error.message throws away the diagnosis.

It appears in Server Components and route handlers calling an internal API by hostname; in generateStaticParams or a page prerendered during next build when the API is not running yet; in Server Actions behind a corporate proxy; and in containers where the host is localhost but the service listens elsewhere.

Quick answer: log error.cause and its code, then fix by class — DNS name, connection refused, TLS trust, proxy routing, or timeout — and give every server-side fetch an AbortSignal so a hang becomes a readable error instead of a stalled render.

Core Mechanics, Signatures & Reproducible Setup

Next.js does not implement fetch. On Node it is the global fetch from undici, wrapped so Next can add caching and revalidation. Undici raises TypeError: fetch failed for every network-layer problem and attaches the original error as cause, sometimes two levels deep for TLS. The wrapper never changes, which is why the message is identical for five unrelated failures.

A reproducible case that fails during build:

ts
// app/posts/page.tsx -- Next.js 16 App Router export default async function Page() { // runs during `next build` because the page has no dynamic API usage const res = await fetch("http://localhost:4000/api/posts"); const posts = await res.json(); return <ul>{posts.map((p: { id: string; title: string }) => <li key={p.id}>{p.title}</li>)}</ul>; }

next build prints TypeError: fetch failed with [cause]: Error: connect ECONNREFUSED 127.0.0.1:4000, because the build machine has no server on port 4000. The page works in the browser and fails in CI, the classic signature of build-time fetching.

Read the chain properly:

ts
export async function safeFetch(url: string, init?: RequestInit) { try { return await fetch(url, { signal: AbortSignal.timeout(8000), ...init }); } catch (error) { const cause = (error as TypeError & { cause?: { code?: string; message?: string } }).cause; console.error("fetch failed", { url, code: cause?.code, detail: cause?.message }); throw error; } }

The mapping from cause to owner:

cause.codeMeaningWho fixes it
ENOTFOUNDDNS name does not resolvethe caller's hostname or DNS config
ECONNREFUSEDnothing listens on that host and portthe server, or the port mapping
EAI_AGAINDNS resolver temporarily unavailablecontainer DNS, retry with backoff
ECONNRESET / UND_ERR_SOCKETpeer closed the socket mid-requestserver keep-alive, proxy idle timeout
DEPTH_ZERO_SELF_SIGNED_CERTTLS chain not trustedCA bundle or certificate
UNABLE_TO_VERIFY_LEAF_SIGNATUREmissing intermediate certificateserver chain order
UND_ERR_CONNECT_TIMEOUTTCP connect timed outnetwork path, firewall, wrong port
UND_ERR_HEADERS_TIMEOUTresponse headers never arrivedupstream latency, raise the timeout

Key Comparison Table

Where the fetch runs decides which failures are even possible:

ContextRuns atCommon causePractical fix
Page prerendered at buildnext buildECONNREFUSED, ENOTFOUNDmark the route dynamic or fetch at request time
Server Component at request timeNode runtimeECONNRESET, TLS errorstimeout, retry, CA config
Route handlerNode runtimeinherited from upstreampropagate status and cause
MiddlewareEdge runtimeENOTFOUND, no TLS optionsavoid private CAs, use absolute URLs
Server ActionNode runtimeproxy and auth errorsdispatcher, cookies forwarding

Caching changes when the failure is observed, not just how often:

OptionNext.js behaviourEffect on failures
cache: "force-cache"response cached across requestsa cached success can hide a now-broken upstream
cache: "no-store"always fetchedevery request can fail visibly
next: { revalidate: 60 }cached for 60 secondsup to 60s of stale errors or stale success
next: { tags: ["posts"] }purge with revalidateTaga failed revalidation keeps the old body
default in Next 16no caching unless opted infailures surface immediately

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. localhost resolves to IPv6 while the server listens on IPv4

Inside many containers localhost maps to ::1 first. A service bound to 127.0.0.1:4000 refuses the IPv6 connection, and the cause reads ECONNREFUSED ::1:4000 while curl 127.0.0.1:4000 succeeds. Use the explicit address, or the Compose service name:

ts
const base = process.env.API_URL ?? "http://127.0.0.1:4000"; const res = await fetch(`${base}/api/posts`, { cache: "no-store" });

Verify the same URL from inside the container before changing code:

bash
docker compose exec web node -e "fetch('http://api:4000/health').then(r=>console.log(r.status)).catch(e=>console.error(e.cause))"

2. next build fetching its own API

A page that fetches /api/... through localhost cannot work at build time: the route handler does not exist until the server runs. Choose one of three honest fixes.

ts
// A. fetch at request time export const dynamic = "force-dynamic"; // B. opt the fetch out of prerendering const res = await fetch(`${process.env.NEXT_PUBLIC_SITE_URL}/api/posts`, { cache: "no-store" }); // C. skip data access during build with an explicit guard if (process.env.NEXT_PHASE === "phase-production-build") return <Skeleton />;

Option A suits a dashboard, B a page that must be fresh, and C only when the page must exist before any data does. Never point a build at localhost and expect a different result in CI.

3. TLS: private CA, missing intermediate, and expired certificates

A self-hosted API behind an internal CA produces fetch failed with cause.code = DEPTH_ZERO_SELF_SIGNED_CERT or SELF_SIGNED_CERT_IN_CHAIN. Do not disable verification for the whole process in production; trust the CA instead:

bash
# Node reads this at startup; works for fetch, https, and undici export NODE_EXTRA_CA_CERTS=/etc/ssl/certs/internal-ca.pem

For a single endpoint, pass a dispatcher:

ts
import { Agent, setGlobalDispatcher } from "undici"; import { readFileSync } from "node:fs"; const ca = readFileSync("/etc/ssl/certs/internal-ca.pem"); setGlobalDispatcher(new Agent({ connect: { ca } }));

The Edge runtime has no such option — middleware uses the platform trust store — so move calls to a private-CA upstream into a Node route handler.

4. Corporate proxy: Node ignores HTTP_PROXY by default

curl succeeds through the proxy and fetch fails with ENOTFOUND or UND_ERR_CONNECT_TIMEOUT, because undici does not read proxy environment variables unless told to:

ts
import { EnvHttpProxyAgent, setGlobalDispatcher } from "undici"; setGlobalDispatcher(new EnvHttpProxyAgent({ httpProxy: process.env.HTTP_PROXY, httpsProxy: process.env.HTTPS_PROXY }));

Create the dispatcher once at startup, in instrumentation.ts or a server-only module. Creating it per request leaks sockets and eventually fails with UND_ERR_SOCKET.

5. Timeouts: turn a hang into a diagnosis

Without a signal, a black-holed connection waits until the platform kills the function, and the log shows a timeout instead of fetch failed. Next 16 supports connection() for dynamic rendering, but it does not bound the socket:

ts
const signal = AbortSignal.timeout(5000); const res = await fetch(url, { signal, cache: "no-store" }); if (!res.ok) throw new Error(`upstream ${res.status}`);

An aborted fetch throws AbortError rather than TypeError, so handle both and log which one happened. Use an AbortController instead of AbortSignal.timeout only when the caller must cancel early, and pair retries with idempotent GETs and 5xx responses.

Common Compilation/Runtime Mistakes & Version Gotchas

Logging only error.message. fetch failed is deliberately generic. Log error.cause and error.cause.code, plus the URL, and the same incident becomes a five-minute fix. A helper like safeFetch above costs nothing and removes the guesswork.

Assuming the failure is in the browser. Server-side fetch has no CORS, no cookie jar, and no browser DNS. A request that works in DevTools can still fail on the server because the host is private, the certificate is self-signed, or the proxy is unset. force-cache compounds this: it can keep serving a body fetched when the upstream was healthy, while no-store exposes every hiccup to users.

Version differences worth knowing. Next.js 15 changed fetch to be uncached by default, so code migrated from 13/14 can suddenly hit the network on every render and surface failures that used to be masked. Next 16 adds cacheComponents and connection(), which make dynamic rendering explicit but do not change undici's error surface. Node 18 ships undici 5 while Node 20+ ships undici 6: EnvHttpProxyAgent and some Agent options are unavailable on the older line, so pin the Node version in CI and production to match.

Verifying the endpoint before debugging Next. Run the same URL through cURL from the same machine and container, then compare status codes with the HTTP status reference. If curl fails too, the problem is infrastructure and no amount of Next configuration will help; if curl works, inspect proxy variables with the env viewer and check whether the Node process sees them.

Reference material: Next.js fetch API reference and Node.js error codes.

Official references

primary documentation

The Next.js documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

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

All Next.js guides

More in Next.js

All Next.js guides

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