mediumDependenciesNext.js (App Router)
The server-side window crash
A developer is building a Next.js App Router application. They asked a chatbot to write a component that reads a value from localStorage on render. When the app is built or server-rendered, it crashes immediately. Why?
ThemeSelector.jsx
export default function ThemeSelector() {
const theme = localStorage.getItem('theme') || 'light';
return (
<div>
<p>Current theme: {theme}</p>
<button onClick={() => localStorage.setItem('theme', 'dark')}>Dark</button>
</div>
);
}What is causing the server-side render crash?
ReferenceError: 'localStorage' is not defined on the server side during pre-rendering/SSR.
The button onClick event handler is executed on the server, triggering database write lockups.
Next.js does not allow reading string variables in components unless imported from 'next/navigation'.
React components cannot render div elements when running under Next.js server mode.
Sign in with GitHub to submit an answer and track your progress.