DEV Community

Discussion on: localStorage with JWT Web Tokens

Collapse
 
torstendittmann profile image
Torsten Dittmann

Great article 👌

I would recommend to save the JWT in a cookie with HttpOnly set. This will be more secure, since localStorage is readable by JavaScript.

Collapse
 
abooayoob profile image
Mohammad Ali Khan

Ditto, localStorage is convenient, but if any of your js dependencies or third party scripts is compromised, that localStorage is up for grabs.

Collapse
 
exanup profile image
Anup Dhakal

I agree, except the part about "more secure". They are just "differently secure/insecure" if that makes sense. While localStorage is vulnerable to XSS attacks, Cookies are not safe from CSRF attacks either. There are ways to strengthen the both. They have other differences as well. Just use whatever is more convenient / suitable for your use-case. Having a soundly secure JWT setup is more important IMHO.

And if you are worried about having some malicious JS (from a compromised library) stealing your tokens, while cookies prevent them from getting the tokens, they cannot prevent the malicious code to act on your behalf anyway!

Collapse
 
torstendittmann profile image
Torsten Dittmann • Edited

You are right, but there is ways to prevent the cookie from being exposed (SameSite, etc). localStorage is always open 😊