Skip to content
Discussion options

You must be logged in to vote

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"

"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.

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by trbgaming100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Programming Help Discussions around programming languages, open source and software development
2 participants