javascriptreactjslocal-storagenext.jsserver-side-rendering

How to use local or session storages in next js


I'm trying to set item to session storage when i get response from my ssr app, but it shows error that session storage is not defined, because in server side there is no storages like that, there is only cookie but I don't need that.

So my question is how can I set items to sessionsStorage from getInitialProps in NextJS


Solution

  • You can not set items to sessionsStorage when calling getInitialProps, because getInitialProps runs on the server side.

    When calling a method of the window object, you can first determine whether the window object is undefined.

    If you use hooks:

    useEffect(() => {
        if (window) { 
          // set props data to session storage or local storage  
        }
    }, []);