DEV Community


Discussion on: localStorage vs cookies: the "tabs vs spaces" sterile debate of web development 🙄

oguimbal profile image
Olivier Guimbal Author • Edited

Totally agree on the "all or nothing situation". But if you assume that your client is somewhat safe, then its safer to never use cookies (you're protecting yourself against XSRF), and prefer passing an 'Authorization' header in your requests filled with a token you'll keep in localStorage.

You've made me realize that this might be another confusion: I'm speaking about SPAs ... for which the only required auth is via Ajax calls (meaning you have control over headers). I'll edit more.

Thread Thread
darkwiiplayer profile image

For SPAs it's a bit easier to use localstorage, but I still think cookies are the place to transmit tokens: their whole point is to transmit certain data with every request, so I don't see much of a point in re-inventing the wheel. For XSRF there's specific mechanisms to mitigate it.

What's more, with cookies, the browser keeps track of what goes to which domain, whereas if you manually insert a header into every fetch request, you might by mistake end up sending the token to the wrong domain, if an attacker finds a way to inject an off-domain URL into your application.

Thread Thread
oguimbal profile image
Olivier Guimbal Author

You can mitigate this very easily. That's what CSPs are for.

Actually, it's much more easy and reliable than mitigating XSRF, given that you just have to do it once, and it does not require any code... (you can just put the right CSP in your CDN config)