Fix: ReferenceError: window is not defined

The Symptom

You deployed a modern web application using a Server-Side Rendering (SSR) framework like Next.js, Nuxt, or SvelteKit. The build fails, or the page instantly crashes on load with the following terminal output:

ReferenceError: window is not defined
  at eval (webpack-internal:///./components/ThemeToggle.js:14:22)

The Cure

The server compiling your code (Node.js/Edge) does not have a browser window object. You must gate off any browser-specific APIs using a strict type check before execution.

Immediate Resolution:

javascript (Vanilla / React / Any)
// WRONG: This crashes the Node.js server during SSR
// const userTheme = window.localStorage.getItem('theme');

// RIGHT: Pure vanilla guard clause
let userTheme = 'dark'; // Provide a safe server fallback

if (typeof window !== 'undefined') {
  // This block is completely ignored by the server
  // It only executes once it hits the client's browser
  userTheme = window.localStorage.getItem('theme') || 'dark';
}

The Breakdown

Modern frontend frameworks generate the initial HTML on a server (Node.js or Edge Runtime) before sending it to the user. The window object, document object, and APIs like localStorage or navigator only exist inside a user's web browser.

When the server tries to read your file to build the HTML, it hits the word window, doesn't know what it is, and throws a fatal ReferenceError. By wrapping the logic in typeof window !== 'undefined', you essentially tell the server: "Skip this part. Leave it for the browser to execute."

Developer Logs

Loading logs...