How to Fix Static Generation Error in Next.js Quickly
getStaticProps or getStaticPaths. To fix this, ensure all data fetching is done inside these functions and avoid using browser-only APIs or asynchronous code outside them.Why This Happens
Next.js static generation runs at build time, so it cannot handle code that depends on runtime data or browser-only APIs. If you try to fetch data dynamically or use window or document inside getStaticProps, it causes errors because these don't exist during build.
export async function getStaticProps() { const data = await fetch('https://api.example.com/data'); const json = await data.json(); const width = window.innerWidth; // This causes error return { props: { json, width } }; }
The Fix
Move all data fetching inside getStaticProps and avoid using browser-specific code there. If you need browser data, get it inside the component using hooks like useEffect. This keeps static generation clean and error-free.
import { useEffect, useState } from 'react'; export async function getStaticProps() { const data = await fetch('https://api.example.com/data'); const json = await data.json(); return { props: { json } }; } export default function Page({ json }) { const [width, setWidth] = useState(0); useEffect(() => { setWidth(window.innerWidth); }, []); return <div>Data length: {json.length}, Window width: {width}</div>; }
Prevention
Always keep static generation code free of browser APIs and runtime-only data. Use getStaticProps and getStaticPaths only for build-time data fetching. Use React hooks inside components for client-side data or effects. Enable ESLint rules like no-undef to catch undefined globals early.
Related Errors
Other common errors include:
- Fallback errors: When
getStaticPathsdoes not return all paths and fallback is misconfigured. - API route errors: Using server-only code in client components.
- Async errors: Forgetting to await promises in data fetching functions.