Next.js App Router – “window is not defined” error when using localStorage #177436
-
|
Hey everyone 👋 ReferenceError: window is not definedHere's the snippet i used: const user = localStorage.getItem("user");It works fine in the browser but crashes during build or SSR. How can I safely use localStorage in Next.js App Router components? Guidelines
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
This happens because Next.js renders components on the server first, and window or localStorage only exist in the browser environment. ✅ Fix: Example 1 — Using "use client" "use client";
import { useEffect, useState } from "react";
export default function Page() {
const [user, setUser] = useState<string | null>(null);
useEffect(() => {
const stored = localStorage.getItem("user");
setUser(stored);
}, []);
return <div>Hello {user ?? "Guest"}!</div>;
}Example 2 — Using conditional check if (typeof window !== "undefined") {
const user = localStorage.getItem("user");
}Extra Tip: |
Beta Was this translation helpful? Give feedback.
This happens because Next.js renders components on the server first, and window or localStorage only exist in the browser environment.
✅ Fix:
Wrap your code so it only runs client-side, either with a useEffect hook or by marking the component as a client component.
Example 1 — Using "use client"
Example 2 — Using conditional check