2

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 },
  };
}
user14587589
  • 449
  • 3
  • 19
  • [`window.localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) is a Web API only available on the browser. `getStaticProps` runs on the server (and at build-time) in a Node.js environment and has no access to `localStorage`. – juliomalves Aug 15 '21 at 17:51
  • @juliomalves is there any way with which i can pass user id then? – user14587589 Aug 15 '21 at 17:56
  • There isn't any way to pass user-specific data using `getStaticProps`. You could look into using `getServerSideProps` instead and [use cookies](https://stackoverflow.com/questions/63860373/how-to-use-cookie-inside-getserversideprops-method-in-next-js) to pass the data, rather than using `localStorage`. – juliomalves Aug 15 '21 at 17:58

1 Answers1

3

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>;
};
Yaya
  • 4,402
  • 4
  • 19
  • 43
  • 1
    But what if i need my userId to fetch data from server? isnt there anyways with which i can pass arguments to my getStaticProps? – user14587589 Aug 15 '21 at 18:07
  • 1
    With SSR, yes but it's not recommended. Therefor SSR isn't useful for apps where we have dynamic routes. You can use `getStaticPaths` it works like getStaticProps but request are limited since with each build it calls the API, and API limits continuous requests – Yaya Aug 15 '21 at 18:14
  • 1
    Here is documentation for `getStaticProps` https://nextjs.org/docs/basic-features/data-fetching#getstaticpaths-static-generation – Yaya Aug 15 '21 at 18:14