Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Next.js: Export encountered errors on following paths

next build stops after prerendering with this summary while the real error sits above. Isolate the failing route, read the source error, and fix the data.

~5 min readNext.js
#Next.js#Build Errors#App Router#Debugging
A Next.js build crate with one amber failed route card, a cyan prerender gate and a log strip beside it

Introduction & Quick Summary

A production build ends like this:

code
Error occurred prerendering page "/blog/hello-world". Error: fetch failed at async getPost (./lib/posts.ts:14:20) Export encountered errors on following paths: /blog/[slug]/page: /blog/hello-world

The line that names the paths is a summary printed after the build worker exits. It is not the error. The cause is the first block above it, usually a stack trace with a file and line, and the path in the summary is only the route where the prerender pass stopped.

Typical causes, in the order they appear in real projects:

  • A fetch that returns 404, times out, or hits a self-signed certificate during the build.
  • cookies(), headers(), or searchParams accessed in a route that Next.js is trying to render statically.
  • generateStaticParams missing or returning a shape that does not match the route segment.
  • A component throwing because the data it received is empty, when the page assumed data exists.
  • Browser-only code at module scope, such as window or localStorage, evaluated during prerender.

Quick answer: reproduce with next build locally, scroll up to the first Error occurred prerendering page block, and fix that route. Do not add dynamic = "force-dynamic" everywhere to make the summary disappear; decide per route whether the page can be static, and make the data path honest.

Core Mechanics, Signatures & Reproducible Setup

Next.js renders every route it can at build time. A Server Component route without a dynamic signal is prerendered on the build machine, and any throw during that pass fails the whole build. The signals that make a route dynamic are narrow:

ts
// app/blog/[slug]/page.tsx export const dynamic = "force-dynamic"; // never prerender this route export const revalidate = 60; // static, refreshed every 60s (ISR) export const dynamicParams = true; // allow slugs not in generateStaticParams export async function generateStaticParams() { const posts = await getPostSlugs(); return posts.map((slug) => ({ slug })); } export default async function Page({ params, }: { params: Promise<{ slug: string }>; }) { const { slug } = await params; const post = await getPost(slug); if (!post) notFound(); return <article>{post.title}</article>; }

A reproducible setup is a route with one dynamic segment, one fetch, and next build in CI-like conditions: production environment variables, no dev server cache, and network access to the data source. Run:

bash
npm run build 2>&1 | tee build.log

Then read the first error block in build.log, not the tail. --debug-prerender keeps stack traces readable when minification is on, and is worth adding while diagnosing.

MessageMeaning
Error occurred prerendering page "/x"first real failure, with stack
Export encountered errors on following pathssummary of failed routes
Static worker exited with code: 1the worker died, usually an uncaught throw
Failed to collect page data for /xmodule-level crash before rendering
Route /x couldn't be rendered staticallydynamic API used under static settings

Key Comparison Table

The fix depends on what the route needs, not on which one makes the build green fastest.

FixKeeps static HTMLUse whenCost
Guard the data and call notFound()yesdata can legitimately be missinga 404 page for missing slugs
generateStaticParamsyesthe route has a finite set of pathsbuild time grows with pages
dynamic = "force-dynamic"nodata is per-request or user-specificslower TTFB, no CDN HTML
revalidate = n (ISR)yescontent changes on a schedulestale window
Wrap in Suspenseyes, streamedslow subtree with a static shellfallback and layout shift
export const dynamicParams = falseyesunknown slugs must 404 at the edgenew slugs need a rebuild

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Read the first error, isolate the route

The summary lists every path that failed. Fixing them in order is faster than guessing, because one broken shared component usually fails many paths at once.

bash
grep -n "Error occurred prerendering page" build.log | head # then read from the first match to the next blank separator sed -n '/Error occurred prerendering page/,/^$/p' build.log | head -40

If a component is shared, one stack trace names it and the rest are symptoms. Fixing that component removes all of them.

2. fetch that fails during the build

A build machine has different DNS, certificates, and rate limits than a developer laptop. A 404 or a failed TLS handshake becomes a prerender failure because the component awaited a rejected promise.

ts
const res = await fetch(`${process.env.API_URL}/posts/${slug}`, { headers: { Authorization: `Bearer ${process.env.API_TOKEN}` }, }); if (!res.ok) { // a missing post is a 404 page, not a broken build notFound(); } const post = await res.json();

Check the status and content type, not just the truthiness of the response. A proxy returning HTML with status 200 makes res.json() throw inside the render, which surfaces as the same prerender error with a confusing stack. The status code reference is a quick way to confirm what the upstream actually returned.

3. cookies() and headers() in a static route

Both are async in current Next.js. Reading them in a route that is being prerendered either throws or forces the route dynamic, depending on the version and configuration. The error text mentions dynamic usage during static generation.

ts
import { cookies } from "next/headers"; export default async function Page() { const store = await cookies(); // must await const theme = store.get("theme")?.value ?? "light"; return <main data-theme={theme}>{/* ... */}</main>; }

If the value changes per request, mark the route dynamic explicitly. If it only personalises a small area, move that part into a Client Component and keep the surrounding page static.

4. generateStaticParams that returns the wrong shape

The function must return one object per path, with keys matching the dynamic segments exactly. A mismatch produces a route list that does not match the page signature, and prerender fails for each entry.

ts
// route: app/blog/[category]/[slug]/page.tsx export async function generateStaticParams() { const posts = await getAllPosts(); return posts.map((p) => ({ category: p.category, slug: p.slug })); }

Returning { slug } for a two-segment route fails, and for catch-all segments the value is an array: { slug: ["a", "b"] }.

5. Empty data that the component assumed was present

A page that assumes a post exists throws on the first slug that was deleted upstream. The build reports it, but only for the deleted path, so the failure looks intermittent.

tsx
export default async function Page({ params }: { params: Promise<{ slug: string }> }) { const { slug } = await params; const post = await getPost(slug); if (!post) notFound(); // stop here, do not render a broken shell return ( <article> <h1>{post.title}</h1> <p>{post.body}</p> </article> ); }

notFound() inside a try block is a trap: it works by throwing a special error, so a catch that swallows errors also swallows the 404 and renders a broken page instead.

6. Browser-only code evaluated at module scope

window, document, and localStorage do not exist on the build machine. Reading them at import time fails every prerendered route that imports the module.

tsx
"use client"; import { useEffect, useState } from "react"; export function ThemeToggle() { const [theme, setTheme] = useState("light"); useEffect(() => { setTheme(localStorage.getItem("theme") ?? "light"); // runs in the browser only }, []); return <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>{theme}</button>; }

Moving the read into an effect is the correct fix for initial state; it also avoids hydration mismatch.

Common Compilation/Runtime Mistakes & Version Gotchas

  • force-dynamic as a blanket fix. It silences the build but removes static HTML from every route, which shows up later as slower TTFB and a lower CDN hit rate. Apply it per route with a reason.
  • output: "export" assumptions. Static export has no server runtime, so cookies(), dynamic routes without generateStaticParams, and Route Handlers that read the request fail at build with this same summary.
  • Build-time environment variables. Anything read from process.env during prerender is baked into the HTML. A missing variable produces a request to undefined/... rather than a clear error.
  • Catching too much. A try/catch around a render that includes notFound() or redirect() converts framework signals into prerender failures.
  • Version drift. Route segment config and async params changed across major versions; code copied from an older tutorial compiles but breaks prerender.
SymptomLikely causeFix
one path fails, others passdata missing for that slugguard and notFound()
every path fails at the same linemodule-level browser APImove into an effect or handler
error mentions dynamic usagecookies or headers in static routeawait and mark dynamic
build passes locally, fails in CIenv var or network differencesame env and network path

Paste a failing API payload into the JSON formatter to confirm it parses before blaming the render, and use the text diff tool when a config change is suspected.

The build output is documented in the next build CLI reference, including the prerender flags, and static generation behaviour per route is described under output configuration. Both are worth reading once before the next upgrade.

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.