Search code examples
javascriptsecuritycookieslocal-storagetoken

Cookie or local storage?


Background: I have two apps frontend and backend. Backend is django with django rest framework. For auth I use token. Client gets the token when it logs in via post. Client sets this token to header and keeps token in localStorage. I save the token to localStorage to prevent second request after reopening the site. But I have written a lot of articles where were wrote that localsStorage is vulnerable and it is susceptible to xss attacks. And now I thing about cookies. But I don't want to rewrite my backend logic. And I'm thinking about writing the token to a cookie via js.

My question: Should I write token to the cookies? Or should I rewrite my backend application and use sessions? Or mb don't rewrite it?


Solution

  • Both cookies and local storage are similarly susceptible to being tampered with on the client-side: the client can see and modify both, and so can any (possibly malicious) extensions they have. But if the connection to your site is over HTTPS and their browser/OS/hardware doesn't have something malicious snooping on things, then there shouldn't be an issue with either cookies or local storage.

    The main difference between them is that cookies get sent to the server with every network request, whereas local storage stays on the user's hard drive and doesn't get sent to the server.

    Cookies are arguably a little bit more vulnerable than local storage because if a cookie gets sent over an unencrypted connection, it can be intercepted - but local storage stays on the client's machine, so there's less chance of it being intercepted by something malicious. But if the connection is encrypted, which it should be, using cookies will be fine.

    If your script requires the token to be sent with requests to the server, you should probably use cookies so you can examine them on your back-end. (If you use local storage instead, you'll have to manually send the token with every request, which is still possible, but a bit inelegant given that cookies can do the same thing without requiring manual intervention on your part.)

    If your script doesn't require the token to be sent with every request, then feel free to use local storage instead if you want. If the server never needs to see the token after it's been generated, then don't use cookies, since it'll be unnecessary overhead for no reason.

    The same general logic above applies to any data on the client-side. If the server often or sometimes needs to see it, cookies are a good choice, if the data isn't too large. If the server never needs to see it, cookies are the wrong choice.