"Next.js Server Components: Why localStorage is undefined"

Next.js Scenario: “Why can’t I use localStorage here?” 😕 “localStorage is undefined…” If you’ve ever tried to use localStorage or window inside a Next.js Server Component, you’ve seen this classic error: ReferenceError: window is not defined At first, it’s confusing — it works fine in React, so why not here? 🧠 The Reason Next.js Server Components run on the server, not the browser. They don’t have access to client-side APIs like window, document, or localStorage. That’s because Server Components are rendered before your app reaches the user’s browser — they exist in Node.js land 🌐 ✅ The Fix If you need to access browser APIs, you must use a Client Component: "use client"; import { useEffect, useState } from "react"; export default function ThemeToggle() { const [theme, setTheme] = useState("light"); useEffect(() => { const saved = localStorage.getItem("theme"); if (saved) setTheme(saved); }, []); return <button>{theme}</button>; } The magic line is: "use client"; That tells Next.js to render it in the browser, where window and localStorage exist. ✅ 💡 Takeaway > Server Components = backend logic. Client Components = browser interactions. Mixing them correctly is what makes Next.js powerful — and tricky. 🗣️ Your Turn Have you faced this window is not defined issue before? How do you decide which parts of your component tree should stay client-side? #Nextjs #ReactJS #WebDevelopment #AppRouter #FrontendDevelopment #CodingTips #ServerComponents #JavaScript #DevCommunity

To view or add a comment, sign in

Explore content categories