Common Next.js errorsReferenceError: window is not defined
ReferenceError: window is not defined (or document, localStorage, navigator) means code that only exists in the browser ran on the server. Next.js renders pages on the server first, even pages full of Client Components.
Why it happens
'use client' doesn't mean "browser only": Client Components still render once on the server to produce the first HTML. Reading window at the top of a component, or importing a library that touches it when it loads, breaks that first render.
How to fix it
Read browser values after the component has mounted:
Read it in an effect 'use client'
import { useEffect, useState } from 'react'
export function Greeting() {
const [name, setName] = useState<string | null>(null)
useEffect(() => {
setName(localStorage.getItem('name'))
}, [])
return <p>Hello{name ? `, ${name}` : ''}</p>
}
For a library that needs the browser as soon as it loads (maps, charts, editors), load it only in the browser from a Client Component:
Load a browser-only library 'use client'
import dynamic from 'next/dynamic'
const Map = dynamic(() => import('./map'), { ssr: false })
Avoid typeof window !== 'undefined' checks that render different HTML on the server and in the browser: that swaps this error for a hydration mismatch.