Local Storage vs Cookies

Victor Mutai
2 min readApr 14, 2021

One of the popular questions I’ve seen in developer forums is, where do I store the JWT token to manage sessions.

There are 2 ways you could store JWT or any other auth tokens, LocalStorage or cookie. Both have their pros & cons but they are vulnerable to XSS attacks.

LocalStorage

  1. Pro: LocalStorage isn’t vulnerable to CSRF. Since LocalStorage data can only be accessed by the domain it originated from other domains cannot access it.
  2. Pro: LocalStorage is an object and can be accessed without messy string conversions.
  3. Con: While cookies can be accessed across different hosts within a domain, LocalStorage can only be accessed within a specific host. This makes things like domain-wide preferences harder to do with LocalStorage.

Cookie

  1. HttpOnly

HttpOnly is an additional flag included in a Set-Cookie HTTP response header. HttpOnly makes sure that the client can’t read the secret via client-side JavaScript.

Con: HttpOnly is designed to prevent any code running on it from access it. That means any javascript framework cannot access it.

2. secure attribute

The secure attribute sets if the cookie should only be read over an HTTPS connection

3. SameSite

SameSite cookies (“First-Party-Only” or “First-Party”) allow servers to mitigate the risk of CSRF and information leakage attacks by asserting that a particular cookie should only be sent with requests initiated from the same registrable domain.

SameSite can help mitigate CSRF vulnerabilities.

Example cookie

Set-Cookie: <name>=<value>[; <Max-Age>=<age>]
`[; expires=<date>][; domain=<domain_name>]
[; path=<some_path>][; secure][; HttpOnly]

Improving your security

While JWT tokens might suffice to authenticate requests, you could also use CSRF tokens for POST requests.

Cross-site request forgery (CSRF) might no longer be a part of the top OWASP threats but that doesn’t mean we should ignore it. A CSRF token is a unique value that is generated on the server-side and transmitted to the client-side. Later when the client makes a request, the CSRF token is included in the request and the server-side validates the token or rejects it if invalid.

Most web frameworks support CSRF protection, and everything is done for you. However, it’s not that straightforward when you are using ReactJS to access a backend API (eg ExpressJS, Django, etc). In such a case, when making calls from ReactJS you need to get the CSRF token from cookies then include it in your requests.

In summary

I have used both localStorage and Cookies, and I found Cookies to be a better option for most use cases. I’m not saying don’t use localStorage. But it’s important to understand the security risks and limitations for both.

--

--