KushagraMish
KushagraMish

Reputation: 335

How I can get localstorage data inside getServerSideProps

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: {},
}

Upvotes: 5

Views: 32208

Answers (2)

Ramakay
Ramakay

Reputation: 3145

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

Upvotes: 5

RobertoMLJr
RobertoMLJr

Reputation: 67

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

Upvotes: 5

Related Questions