Fix guides / Next.js "ReferenceError: window is not defined"
How to fix "ReferenceError: window is not defined" in Next.js
Your Next.js build or page load fails with ReferenceError: window is not defined (or document is not defined, or localStorage is not defined). The code is fine in a browser. The problem is that Next.js also runs it on the server.
Why it happens
Next.js renders pages on the server first, in Node.js, where there is no browser: no window, document, or localStorage. Even components marked 'use client' are rendered on the server once for the initial HTML. Any code that touches browser objects while rendering, or at the top level of a file, crashes there.
Fix 1: move browser code into useEffect
'use client';
import { useEffect, useState } from 'react';
export default function ThemeToggle() {
const [theme, setTheme] = useState('light');
useEffect(() => {
// runs only in the browser, after the first render
setTheme(localStorage.getItem('theme') ?? 'light');
}, []);
return <button>{theme}</button>;
}
Fix 2: load a browser-only library on the client
Map, chart, and editor libraries often touch window as soon as they are imported. Load them only in the browser:
'use client';
import dynamic from 'next/dynamic';
const Map = dynamic(() => import('./Map'), { ssr: false });
In the App Router, ssr: false must be used inside a Client Component (a file with 'use client').
Fix 3: import inside the effect
useEffect(() => {
import('some-browser-lib').then((lib) => lib.init());
}, []);
What not to do
Avoid if (typeof window !== 'undefined') inside the JSX you render. It stops the crash but makes the server and browser output differ, which causes a hydration error instead. Use it only inside functions that run on events or in effects.
How to verify
Run npm run build locally. Server-side rendering errors show up there before you deploy.
Request a fix
Last updated 2026-10-19.