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.

Introduction & Quick Summary
A production build ends like this:
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-worldThe 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
fetchthat returns 404, times out, or hits a self-signed certificate during the build. cookies(),headers(), orsearchParamsaccessed in a route that Next.js is trying to render statically.generateStaticParamsmissing 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
windoworlocalStorage, 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:
// 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:
npm run build 2>&1 | tee build.logThen 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.
| Message | Meaning |
|---|---|
Error occurred prerendering page "/x" | first real failure, with stack |
Export encountered errors on following paths | summary of failed routes |
Static worker exited with code: 1 | the worker died, usually an uncaught throw |
Failed to collect page data for /x | module-level crash before rendering |
Route /x couldn't be rendered statically | dynamic 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.
| Fix | Keeps static HTML | Use when | Cost |
|---|---|---|---|
Guard the data and call notFound() | yes | data can legitimately be missing | a 404 page for missing slugs |
generateStaticParams | yes | the route has a finite set of paths | build time grows with pages |
dynamic = "force-dynamic" | no | data is per-request or user-specific | slower TTFB, no CDN HTML |
revalidate = n (ISR) | yes | content changes on a schedule | stale window |
Wrap in Suspense | yes, streamed | slow subtree with a static shell | fallback and layout shift |
export const dynamicParams = false | yes | unknown slugs must 404 at the edge | new 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.
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 -40If 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.
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.
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.
// 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.
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.
"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-dynamicas 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, socookies(), dynamic routes withoutgenerateStaticParams, and Route Handlers that read the request fail at build with this same summary.- Build-time environment variables. Anything read from
process.envduring prerender is baked into the HTML. A missing variable produces a request toundefined/...rather than a clear error. - Catching too much. A
try/catcharound a render that includesnotFound()orredirect()converts framework signals into prerender failures. - Version drift. Route segment config and async
paramschanged across major versions; code copied from an older tutorial compiles but breaks prerender.
| Symptom | Likely cause | Fix |
|---|---|---|
| one path fails, others pass | data missing for that slug | guard and notFound() |
| every path fails at the same line | module-level browser API | move into an effect or handler |
| error mentions dynamic usage | cookies or headers in static route | await and mark dynamic |
| build passes locally, fails in CI | env var or network difference | same 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 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.