Next.js getStaticProps localstorage is not defined

Viewed 2937

I have my user id stored in local storage and I want to access it in the getStaticProps to fetch the subscribers of current user but I am getting Local storage is not defined error.

Any solutions please?

Here is my code:

export async function getStaticProps() {
  const userData = {
    id: localStorage.getItem("user_id"),
  };
  const subscribersAPi = await fetch(
    `url for server`
  );
  const result = await subscribersAPi.json();
  return {
    props: { data: result },
  };
}
1 Answers

localStorage, sessionStorage are among Window Object methods that Browser provides us. Learn more!

When server renders the app in SSR, there will be no Browser therefor no window exists, thus you cannot access local storage.
Instead you should access them in window with an useEffect

const MyComponent = () => {
  const [data, setData] = useState("");

  useEffect(() => {
    setData(localStorage.getItem("myData"));
  }, []);

  return <div>{data}</div>;
};
Related