← All errors · Next.js
ReferenceError: window is not defined
Exact error
ReferenceError: window is not defined
What it means
Code that touches a browser global (window, document, localStorage) ran on the server during server rendering or build, where those globals don't exist.
Likely causes
- Accessing window/document at the top level of a module or during render.
- Importing a library that assumes a browser at import time.
How to fix it
Access browser globals inside useEffect, which only runs in the browser:
useEffect(() => { const saved = window.localStorage.getItem('theme'); }, []);Or guard the access:
if (typeof window !== 'undefined') { // browser-only code }For browser-only libraries, load the component with next/dynamic and { ssr: false }.
Related errors
- Hydration failed because the initial UI does not match what was rendered on the server
- You're importing a component that needs useState. It only works in a Client Component
Get new fixes weekly
No spam. Unsubscribe anytime. Privacy