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.

Introduction & Quick Summary
A Server Component or route handler fails with a message that says nothing useful:
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:
// 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:
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.code | Meaning | Who fixes it |
|---|---|---|
ENOTFOUND | DNS name does not resolve | the caller's hostname or DNS config |
ECONNREFUSED | nothing listens on that host and port | the server, or the port mapping |
EAI_AGAIN | DNS resolver temporarily unavailable | container DNS, retry with backoff |
ECONNRESET / UND_ERR_SOCKET | peer closed the socket mid-request | server keep-alive, proxy idle timeout |
DEPTH_ZERO_SELF_SIGNED_CERT | TLS chain not trusted | CA bundle or certificate |
UNABLE_TO_VERIFY_LEAF_SIGNATURE | missing intermediate certificate | server chain order |
UND_ERR_CONNECT_TIMEOUT | TCP connect timed out | network path, firewall, wrong port |
UND_ERR_HEADERS_TIMEOUT | response headers never arrived | upstream latency, raise the timeout |
Key Comparison Table
Where the fetch runs decides which failures are even possible:
| Context | Runs at | Common cause | Practical fix |
|---|---|---|---|
| Page prerendered at build | next build | ECONNREFUSED, ENOTFOUND | mark the route dynamic or fetch at request time |
| Server Component at request time | Node runtime | ECONNRESET, TLS errors | timeout, retry, CA config |
| Route handler | Node runtime | inherited from upstream | propagate status and cause |
| Middleware | Edge runtime | ENOTFOUND, no TLS options | avoid private CAs, use absolute URLs |
| Server Action | Node runtime | proxy and auth errors | dispatcher, cookies forwarding |
Caching changes when the failure is observed, not just how often:
| Option | Next.js behaviour | Effect on failures |
|---|---|---|
cache: "force-cache" | response cached across requests | a cached success can hide a now-broken upstream |
cache: "no-store" | always fetched | every request can fail visibly |
next: { revalidate: 60 } | cached for 60 seconds | up to 60s of stale errors or stale success |
next: { tags: ["posts"] } | purge with revalidateTag | a failed revalidation keeps the old body |
| default in Next 16 | no caching unless opted in | failures 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:
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:
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.
// 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:
# Node reads this at startup; works for fetch, https, and undici
export NODE_EXTRA_CA_CERTS=/etc/ssl/certs/internal-ca.pemFor a single endpoint, pass a dispatcher:
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:
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:
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 documentationThe Next.js documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Next.js guides
All Next.js guidesModule not found: Can't resolve a package or alias in Next.js
TypeScript and the bundler resolve imports separately. Align path aliases, workspace dependencies, exports conditions and filename case.
Next.js 16 DynamicServerError: cookies(), headers() and fetchCache
Request-time APIs make a route dynamic, and Next 16 replaced the segment configs with Suspense boundaries and use cache. What to delete and what to wrap.
Next.js cacheComponents: 'used uncached or runtime data' build error
Cache Components makes the build refuse to guess where the static shell ends. Stream it, cache it with use cache, or declare the route blocking.
next/font: Failed to fetch a Google font during the build
The font is fetched during the build, not at runtime. Vendor it with next/font/local or give CI and Docker a route out.
More in Next.js
All Next.js guidesThe guides filed next to this one in Next.js, in library order.