4

I am using NextJS 12. I am trying to get local storage object. When I use localstorage inside getServerSideProps I get an error like this ReferenceError: localStorage is not defined. I tried to use it outside the function as well but I still get this error. Is there any way to use it inside getServerSideProps.

export async function getServerSideProps({ query }) {
    const id = query.id;
    const getData = JSON.parse(localStorage.getItem("form"));
    console.log(getData)
  
    return {
      props: {},
}

2 Answers 2

5

Welcome to StackOverflow, as it refers in the documentation

If you export a function called getServerSideProps (Server-Side Rendering) from a page, Next.js will pre-render this page on each request using the data returned by getServerSideProps.

Localstorage is only available on the client side and you are trying to access it in a server side only function , you can use something like

if (typeof window !== 'undefined') {
// your code 
  const id = query.id;
    const getData = JSON.parse(localStorage.getItem("form"));
    console.log(getData)
  
}

Please review this article to get more information on running client side only code.

Another approach would be to use a dynamic import where the hello3 component would contain the code accessing local storage.

import dynamic from 'next/dynamic'

const DynamicComponentWithNoSSR = dynamic(
  () => import('../components/hello3'),
  { ssr: false }
)

function Home() {
  return (
    <div>
      <Header />
      <DynamicComponentWithNoSSR />
      <p>HOME PAGE is here!</p>
    </div>
  )
}

export default Home
5

Another way would be using cookies instead of using localstorage, I had the same problem when I developed my last application and I solved it using the nookies package

Nookies: A collection of cookie helpers for Next.js

2
  • Nice recommendation..
    – Jhonny Jr.
    Oct 30, 2022 at 8:17
  • @JhonnyJr. Cookie is not a replacement for storage. Aug 23 at 22:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.