Search code examples
reactjscookiesnext.jsjwtuse-state

Nextjs - How Do I Store A JWT in The Client's Browser That Can Persist A Browser Restart


I am making an app that involves creating a JWT that the client must "remember" for at least 24 hours. I know that sounds strange but this app I'm building involves something called "Litprotocol" which does decentralized authorization. When a user logs in/registers, a JWT is created by a series of 3rd party servers, and the resulting JWT is valid for 24 hours. Since this JWT involves a somewhat intricate process, for efficiencies sake, I don't want to create a new JWT every time the user tries to login. The app is written in Nextjs and I tried to use the following code to attempt creating a persistently stored variable name "storedVal."

export default function Home(props: any) {

...
...
...

  const [storedVal, setStoredVal] = useState(String);

  function storePersistence() {
    setStoredVal('I set this');
  }

  function printPersistence() {
    console.log(storedVal);
  }

  return (

    <>
      <VStack>
        <Heading as='h3'>Connect to see unity app</Heading>

        {
          !connected ? <Button variant='solid' onClick={connect}>Connect</Button> : <Text>Now you can click on protected path link at the bottom</Text>
        }<br></br>

        <Button variant='solid' onClick={storePersistence}>Store Persistence</Button>
        <Button variant='solid' onClick={printPersistence}>Check Persistence</Button>

      </VStack>
    </>
  )
}

The "Store Persistence" and "Check Persistence" buttons and functions are the relevant code. This doesn't work. As soon as I restart my browser, "storedVal" is cleared. So how can I make "storedVal" persist browser and possibly computer restarts?


Solution

  • General Idea/Mechanism for persisting data via localStorage/sessionStorage in client side.

    1. Store it in localStorage when JWT is sent to client.
    2. When user closes the site and open again that time fetch JWT from localStorage and check if it's valid or not and do the needful. Refer Blog for localstorage.
    3. You can set JWT as follows localStorage.setItem("jwt", value) and fetch it localStorage.getItem("jwt")

    You can use hooks/function provided by library/framework as well it does work on similar idea.