How to use local or session storages in next js

Viewed 17157

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

3 Answers

I've created a custom hook for this to avoid SSR errors. The code inside the useEffect hook will be executed on client side only so you do not need to check window.

hooks/useSessionStorage.js

import { useState, useEffect } from "react";

const useSessionStorage = (name) => {
  const [value, setValue] = useState('')

  useEffect(() => {
    setValue(sessionStorage.getItem(name))
  }, [])

  return value
}

export default useSessionStorage

SomeComponent.js

import useSessionStorage from '../hooks/useSessionStorage'

const SomeComponent = () => {
  const zipCode = useSessionStorage('zipCode')

  return (
    <input value={zipCode} />
  )
}

getInitialProps would be executed in client-side or in server-side. So, you need to prevent access sessionStorage in server-side.

Page.getInitialProps = async (context) => {
  if (typeof window !== 'undefined') {
    window.sessionStorage.set('item', 'itemValue')
  }
}

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  
    }
}, []);
Related