0

I'm new to react and I wanna know how to store a string like a JSON Web Token in the browser after user logs in...?

And also how to remove when user logs out?

PatMan10
  • 568
  • 2
  • 5
  • 15
  • https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage – SpeedOfRound May 08 '19 at 20:01
  • 4
    ***SECURITY ADVICE***: do ***not*** store JWT inside `localStorage` or `sessionStorage`, use HTTP-only cookies instead ([1](https://stackoverflow.com/questions/44133536/is-it-safe-to-store-a-jwt-in-localstorage-with-reactjs), [2](https://dev.to/rdegges/please-stop-using-local-storage-1i04), [3](https://security.stackexchange.com/questions/175783/is-the-owasp-recommendation-regarding-localstorage-still-valid)) – Nino Filiu May 08 '19 at 20:07

1 Answers1

2

When the component mounts or in the constructor, you can check to see if the user's browser has this data already using localstorage.getItem('webToken') and/or set it using localstorage.setItem('webToken', token). To clear it on logout you could remove it by using localstorage.removeItem('webToken').

See local storage docs

It should be noted that users may not click log out, but instead just leave or close the page. This means it is possible that the local storage item will persist on the next page load. Since local storage does not expire, this could pose potential issues.

Josh Sanger
  • 784
  • 4
  • 7