Back to Feed

Next.js Build Error: "ReferenceError: window is not defined" in Navbar

@Deep Chauhan

Context

I am building the navigation bar using Next.js 14 (App Router). I need to read a "theme" value from localStorage to set Dark Mode. I cannot use a database for this preference.

What broke

I tried to read localStorage directly at the top of my component: const theme = localStotrage.getItem('theme'). It worked perfectly on my localhost but not working when i treid 'npm run build'.

Reasoning

1. I was confused because it worked in the browser. 2. I realized that Next.js tries to render the page on the SERVER first to generare HTML.

The Fix / Solution

// BAD CODE:
// const theme = localStorage.getItem('theme');
// FIXED CODE:
const [theme, setTheme] = useState('light');
useEffect(() => {
// This only runs in the browser
const stored = localStorage.getItem('theme');
if (stored) setTheme(stored);
}, []);