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

Time:06-25

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?

CodePudding user response:

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.

CodePudding user response:

Aside from @GodWin's comment, you could also use this hook which I love: useLocalStorage. There's many variants of it and you can certainly write your own. It basically loads in a localStorage value into a hook given a key, for which you can provide a default value.

You can use it just like a useState:

function Home() {
  const key = "local-jwt"
  const defaultValue = null
  const [jwt, setJWT] = useLocalStorage(key, defaultValue)

  // use your jwt somewhere

  return (
    ...
  )
}
  • Related