Skip to content
Latchkey

Next.js "Error occurred prerendering page" (getStaticProps)

Next runs getStaticProps/getStaticPaths at build time to prerender pages. If that code throws - a failed fetch, an undefined access, a missing env var - the static export of that page fails and the whole build stops.

What this error means

The build fails with Error occurred prerendering page "/path" followed by the real error and a Next "prerender-error" link. It happens during the "Generating static pages" phase, not at runtime.

next build output
Error occurred prerendering page "/blog/[slug]". Read more: https://nextjs.org/docs/messages/prerender-error
TypeError: Cannot read properties of undefined (reading 'title')
    at getStaticProps (/app/.next/server/pages/blog/[slug].js:30:21)

> Build error occurred
Error: Export encountered errors on following paths:
  /blog/[slug]

Common causes

Data fetch fails at build time

A fetch in getStaticProps hits an API that is unreachable from CI, returns a non-200, or returns a shape the code does not guard, so a downstream access throws.

Missing build-time environment variable

An API base URL or token read from process.env is set locally but not in CI, so the fetch goes to undefined or is unauthorized.

getStaticPaths returns a path with no valid props

A slug returned by getStaticPaths has no corresponding data, so getStaticProps for that path throws instead of returning notFound: true.

How to fix it

Handle fetch failures and bad data

Check responses and return notFound/redirect instead of letting an access throw.

pages/blog/[slug].tsx
export async function getStaticProps({ params }) {
  const res = await fetch(`${process.env.API_URL}/posts/${params.slug}`)
  if (!res.ok) return { notFound: true }
  const post = await res.json()
  if (!post?.title) return { notFound: true }
  return { props: { post } }
}

Provide build-time env vars in CI

Set every variable the prerender reads in the build job, not just at runtime.

.github/workflows/ci.yml
- run: npm run build
  env:
    API_URL: ${{ secrets.API_URL }}

How to prevent it

  • Guard every build-time fetch (check res.ok, validate the shape).
  • Return notFound/redirect for missing data instead of throwing.
  • Mirror all required env vars into the CI build step.

Frequently asked questions

What causes ""Error occurred prerendering page""?
A fetch in getStaticProps hits an API that is unreachable from CI, returns a non-200, or returns a shape the code does not guard, so a downstream access throws.
How do I fix "Error occurred prerendering page"?
Check responses and return notFound/redirect instead of letting an access throw.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card