On HTML5, we can use localStorage to keep data persistently on client side. It seems better from a non-security point of view (easy to access, not 5mb limit like cookies, etc).


From a security point of view, Which method is more secure against a XSS attack? localStorage or cookies?

  • Javascript can access your local storage, which means in case of XSS this data can be read. So it really depends what kind of data you want to store.
    – Jeroen
    Sep 1, 2017 at 7:31
  • Since you can set the httpOnly attribute on your cookies, this seems more secure to me.
    – Jeroen
    Sep 1, 2017 at 7:39
  • Cookies are sent to the server with every request! If you use the data in client side JavaScript, this creates network traffic for no good reason. It also gives a chance to steal them with every request (a small chance when using https, but still above zero).
    – Josef
    Sep 1, 2017 at 9:21
  • @Jeroen When you compare cookies to localstorage, then you are talking about client-sided javascript. That means you are only talking about cookies which do not have the http-only flag.
    – Philipp
    Sep 1, 2017 at 9:52
  • @Philipp: Yes, you are right! I was wrong.
    – Jeroen
    Sep 1, 2017 at 10:02

1 Answer 1


Both cookies and localstorage are accessed via JavaScript APIs. When the attacker can inject JavaScript into the target's html document, they can read and write them equally.

A comment mentions http-only cookies. But those can not be accessed by client-sided JavaScript applications at all, so they are not competing with localstorage in most scenarios.

But one thing you need to keep in mind is that there is no such thing as a javascript-only cookie. When you store confidential information in a cookie, that information will be sent to the server with every request. When you don't use https, then it will be sent unencrypted. This has nothing to do with XSS injections, though.

  • 2
    Another minor security benefit of local storage is that you can't accidentally misconfigure the origin or access things from a parent domain; data in local storage is accessible only for the domain that set it.
    – Polynomial
    Sep 1, 2017 at 11:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .