Course contentsShow
← React
Lesson 1623 of 2,39639. Server Components in PracticeFree lesson

When You MUST Use Client: Browser APIs

Accessing window, document, localStorage, or other browser-only globals requires a Client Component.

When You MUST Use Client: Browser APIs

What you'll learn: Why accessing browser-specific globals like window, document, or localStorage requires a Client Component, and how to handle this boundary correctly.

The Browser-Only Zone

Server Components run on the server — which means they have no access to browser APIs. There's no window object in Node.js, no document.getElementById(), no localStorage to read from. If your component needs to interact with these browser-specific features, it must be a Client Component.

Think of it like a phone call: the server is in a data center somewhere, while browser APIs are like looking out the window of your home. The server can't "look out your window" — it's in a completely different location.

Common Browser APIs That Require 'use client'

  • Window API: window.innerWidth, window.location, window.scrollTo()
  • Document API: document.querySelector(), document.title
  • Storage APIs: localStorage, sessionStorage
  • Navigator API: navigator.geolocation, navigator.clipboard
  • Browser-only Web APIs: IntersectionObserver, ResizeObserver, MediaRecorder

The Pattern

If you need to read localStorage, measure window dimensions, or access any other browser-only feature, mark that component (or its parent boundary) with 'use client':

'use client'

export function ThemeToggle() {
  const savedTheme = localStorage.getItem('theme')
  // This only works in Client Components
}

The key is to place 'use client' at the lowest point where you need browser access, keeping as much of your tree as Server Components.

Key Takeaway: Browser APIs like window, document, and localStorage only exist in the browser — any component that accesses them must be marked with 'use client' to ensure it runs on the client side.