next build fails while prerendering pages
Export encountered errors on following pathsShort answer
This build error means one or more pages threw while Next.js prerendered them. The listed path is the page. Run next build with --debug-prerender to get an unminified stack trace, then fix the usual three causes: browser-only APIs on the server, props that are empty at build time, or cookies and headers used outside the render.
Fix it fast
1Find out which cause you have
Rebuild with debug output. The stack trace then names the component and route that threw.
npx next build --debug-prerender2Match what you see, then jump to its fix
- 1
A browser API such as window, localStorage or navigator appears in the stack traceA component uses a browser API during server renderingFix - 2
The stack trace points at code that reads props or fetch results that are empty at build timeData is missing at build timeFix - 3
DynamicServerError: Dynamic server usagecookies() or headers() runs outside the render call stackFix
- 1
What does the error look like?
Export encountered errors on following pathsDynamicServerError: Dynamic server usage
Cause 1 of 3
A component uses a browser API during server rendering
1Check
Client Components are also prerendered to HTML at build time, where window and similar APIs do not exist.
grep -rn "window\.\|localStorage\|document\." app components2Fix
Read the browser API inside useEffect, or load the component with dynamic and ssr: false.
'use client'
import { useEffect, useState } from 'react'
export default function Width() {
const [w, setW] = useState(0)
useEffect(() => setW(window.innerWidth), [])
return <p>{w}</p>
}3Verify
Run the build again.
npx next buildConfirmed by nextjs.org
Cause 2 of 3
Data is missing at build time
1Check
Props or fetch results can be empty during prerendering, for example when an API is not reachable from the build machine.
curl -sS -o /dev/null -w "%{http_code}\n" https://api.example.com/posts2Fix
Handle the empty case. In the Pages Router return notFound: true from getStaticProps when the data is missing.
export async function getStaticProps(context) {
const data = await fetchData(context.params.id)
if (!data) {
return { notFound: true }
}
return { props: { data } }
}3Verify
Build again; the route should either render or be skipped as 404.
npx next buildConfirmed by nextjs.org
Cause 3 of 3
cookies() or headers() runs outside the render call stack
1Check
Calling cookies() or headers() inside setTimeout, setInterval, or without awaiting a promise loses the async context during the static build.
grep -rn "setTimeout\|setInterval" app | head2Fix
Call cookies() first, then pass the value into the callback.
import { cookies } from 'next/headers'
async function getCookieData() {
const cookieStore = await cookies()
const cookieData = cookieStore.getAll()
return new Promise((resolve) =>
setTimeout(() => resolve(cookieData), 1000)
)
}3Verify
Run the build.
npx next buildConfirmed by nextjs.org
How do I stop it coming back?
- Run next build in CI on every pull request, not just next dev locally.
- Keep window, document and localStorage reads inside effects.
- Make the build machine able to reach every API the pages fetch from.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Back end
next build stops with: Failed to collect page data for a route
Error: Failed to collect page data for /dashboard
Failed to collect page data for a route is the last line of a failed build, not the cause.
3 causes, each with a fixWeb apps
Apollo Server rejects a request as a potential CSRF
HTTP 400 Bad Request from the GraphQL endpoint
Apollo Server's CSRF prevention is on by default.
3 causes, each with a fixWeb apps
Clerk cannot read its publishable key in a Next.js app
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY is undefined
Clerk reads NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY.
3 causes, each with a fixWeb apps
The shell cannot find create-next-app
command not found: create-next-app
create-next-app is not meant to be installed as a shell command.
2 causes, each with a fixWeb apps
ESLint fails with: Cannot find module 'next/babel'
ESLint stops on the first file with a Babel or parser error instead of listing lint results
next/babel is a Babel preset that ships inside the next package.
3 causes, each with a fixWeb apps
Firebase Auth says the API key is not valid
Firebase: Error (auth/api-key-not-valid.-please-pass-a-valid-api-key.)
The apiKey your app sends is either empty, wrong, or blocked.
4 causes, each with a fix