Course contentsShow
← React
Lesson 1655 of 2,39640. Server-Side RenderingFree lesson

Common Cause: Browser-Only APIs

Identifying mismatches from using window, localStorage, or document during initial render on the server.

Common Cause: Browser-Only APIs

What you'll learn: Why using browser-specific APIs like window, localStorage, or document during initial render causes hydration mismatches in SSR apps.

The Server Has No Browser

When React renders your components on the server, the server environment has no browser. There's no window object, no localStorage, no document. These APIs simply don't exist in Node.js.

If your component tries to access these during render, one of two things happens:

  1. On the server: The code crashes (ReferenceError: window is not defined) or you get undefined
  2. On the client: The code runs successfully and produces a value

This creates a mismatch: the server rendered one thing (maybe an error fallback, or nothing), but the client tried to hydrate with different content (the actual browser API value).

The Timing Problem

The issue isn't that you can't use browser APIs—it's that you can't use them during the initial render that happens on both server and client. React expects the first client render to produce identical output to what the server sent.

// ❌ Causes hydration mismatch
function BadComponent() {
  const theme = window.localStorage.getItem('theme'); // Crashes on server!
  return <div>{theme}</div>;
}

The server can't access localStorage, so it either errors or renders nothing. The client can access it, rendering "dark" or "light". Mismatch!

The Solution Preview

You'll need to defer browser API access until after hydration completes—but that's a technique you'll learn in the next lessons.

Key Takeaway: Browser APIs like window, localStorage, and document don't exist on the server, so accessing them during render creates hydration mismatches between server HTML and client expectations.