Home > Back-end >  ReferenceError: window is not defined in getServerSideProps for Next.js App And I Need to Store A Va
ReferenceError: window is not defined in getServerSideProps for Next.js App And I Need to Store A Va

Time:06-25

This is my getServerSideProps code:

//@ts-ignore
export async function getServerSideProps({ req, res, query }) {
  const { id } = query
  const cookies = Cookies(req, res)
  const jwt = cookies.get('lit-auth')
  if (!jwt) {
    return {
      props: {
        authorized: false
      },
    }
  }

  const { verified, payload } = LitJsSdk.verifyJwt({ jwt })
  console.log(verified)
  console.log(payload)
  if (
    payload.baseUrl !== "http://localhost:3000"
    || payload.path !== '/protected'
    || payload.extraData !== id
  ) {
    return {
      props: {
        authorized: false
      },
    }
  }

  storePersistence(payload)

  return {
    props: {
      authorized: verified ? true : false
    },
  }
}

function storePersistence(payload: string) {
  window.localStorage.setItem('lit_protocols_jwt', payload);
}

I

This is the error I get in my console

error - src/pages/protected.tsx (199:2) @ storePersistence
ReferenceError: window is not defined
  197 | 
  198 | function storePersistence(payload: string) {
> 199 |   window.localStorage.setItem('lit_protocols_jwt', payload);
      |  ^
  200 | }
  201 | 

How can I store payload persistently in the client's browser? I'd be willing to try some other method if you can think of one but I need the client's browser to retain payload for future access.

CodePudding user response:

You can persist the data in the cookies. You can do so from scratch with

res.header('set-cookie: key=value; max-age=2592000');

Add retrieve cookies from document.cookie. Or use a library like cookies-next.

import { setCookies, getCookie  } from 'cookies-next';

setCookies('key', 'value', options);
getCookie('key', options); // => 'value'
  • Related