How to store JWTs in browser-based apps

I went through the following options:

  1. Web Storage (localStorage or sessionStorage)
  2. HTTP-only cookie
  3. Javascript accessible cookie ignored by server-side

in what can be described as possibly my longest answer on StackOverflow so I’ll just transcribe the conclusions here and for full details you can check the answer.

Conclusions

The recommendation for most common scenarios would be to go with Option 1, mostly because:

  • If you create a Web application you need to deal with XSS; always, independently of where you store your tokens
  • If you don’t use cookie-based authentication CSRF should not even pop up on your radar so it’s one less thing to worry about

Also note that the cookie based options are also quite different, for Option 3 cookies are used purely as a storage mechanism so it’s almost as if it was an implementation detail of the client-side. However, Option 2 means a more traditional way of dealing with authentication; for a further read on this cookies vs token thing you may find this article interesting: Cookies vs Tokens: The Definitive Guide.

Finally, none of the options mention it, but use of HTTPS is mandatory of course, which would mean cookies should be created appropriately to take that in consideration.

Advertisement