A bag with a bunch of Cookies

LocalStorage and Cookies under the hoodies

Explaining why they're not concurrent

It is usual, as developers, to use tools that we don’t entirely understand. Web storage on browsers and cookies are examples of things we use without knowing what is happening behind the scenes. In this post, we’re going to talk about it and try to demystify these tools.

What is web storage?

First things first, according to MDN, The Web Storage API
provides mechanisms by which browsers can store key/value pairs, in a much more intuitive fashion than using cookies
.  We have two methods available to use within Web Storage: window.sessionStorage and window.localStorage.

They work mostly the same both maintain a separate storage area for each given origin. SessionStorage does it for a page session (as long as the browser or tab is open, including reloads and restores) whereas localStorage persists even when the browser is closed.

Invoking one of these methods will create a Storage object, and a different object is used for sessionStorage and localStorage for each origin (they function and are controlled separately).

Why do we have storage on browsers?

The main purpose is being an alternative to Cookies. Cookies were, for a while, the only way to persist data on the client-side because no data is transmitted to the server in every HTTP request.

So, we can boost our application performance, save user preferences, keep the application state across multiple sessions or even different computers by using this storage.

Advantages and traps using web storage

They are very secure to set/retrieve information — A SecurityError will be thrown in one of these cases:

  • The origin is not a valid scheme/host/port tuple. Two objects have the same origin only when the scheme, hostname, and port all match — MDN. This means that you can only set/get data on your browser.
  • If the request violates the policy decision (user has configured the browser to prevent persisting data, for example).

But not everything is flowers, and, of course, we have to consider some things before using these tools:

  • Both sessionStoratge/localStorage are synchronous and will block the main thread.
  • Any JavaScript code on your page can access local storage.
  • They are also limited to at most 5 MB.
  • Can contain only strings.

Cookies

What are cookies?

Cookies, not the oracle’s one, are small pieces of data that a server sends to a user’s browser. It’s often used to tell if two requests come from the same browser (to keep a user logged in, for example), store user preferences, and record and analyze the user’s behavior.

As I told you, they are sent with every HTTP request, so storing anything more than a small amount of data will significantly increase the size of every web request, and this explains why modern browsers recommend using the Web Storage API rather than Cookies.

However, later in this post, we’re going to see trade-offs of using Cookies and Web Storage API.

How does it work?

Servers can send one or more Set-Cookie headers along with the response — check this link if you’re not familiar with how the HTTP protocol works — the browser usually stores it (unless the user doesn’t want to) and sends it with requests made to the same server inside a Cookie HTTP. You can also set additional restrictions to a specific domain and path to limit where the cookie is sent.

To clarify things up:

/* Server will set this attribute within the response to the client
 * it is basically and "order" to browser store these pair of cookies 
 */
Set-Cookie : <cookie-name>=<cookie-value>

/* Then, with every subsequent request to the server the browser sends
 * all previously stored cookies back to the server using the Cookie header.
 */

GET /sample_page.html HTTP/2.0
Host: www.example.org
Cookie : moonshadow=sunflower; frodo=ira

Right, you’re convinced that Cookies are good to send and receive data from a server, and you are correct, but who will guarantee the authenticity of the request? The good news, you can ensure that cookies are sent securely and not accessed by unintended parties or scripts in one of two ways: with the Secure attribute and the HttpOnly attribute.

A cookie with the Secure attribute is sent over the HTTPS protocol with an encrypted request, and it is never sent with unsecured HTTP (except on localhost), preventing man-in-the-middle attacks.

The HttpOnly attribute is used (strongly recommend using it) because it turns the Document.cookie API inaccessible to client JavaScript. It is very helpful to mitigate cross-site scripting (XSS).

We also have the Domain attribute that specifies which hosts can receive a Cookie. If the server doesn’t specify a domain, the browser will set the domain to the same host that set the cookie.

When should we use one rather than the other?

All good, now let’s talk about use cases for these two guys. The Web Storage API was not designed to be the more secure way to store data — Any JavaScript code on your page can access local storage — which means that it’s not the best place to store sensitive information

Although, we can do it by saving a JWT (JSON Web Token), for example in our local/session storage alongside other security policies:

  • Ensure the entire site was served over HTTPS
  • Ensure the use of HSTS
  • Add the X-Frame-Options header to every HTTP response, and set it to Deny
  • Set X-XSS-Protection to 1
  • Set X-Content-Type-Options to nosniff
  • Make sure Content-Security-Policy is restricted to your domain name, and any CDNs you may be pulling scripts in from
  • Set Referrer-Policy to same-origin
  • Limit the JWT expiry to 1 hour

Check this out for further information

Fortunately, Cookies have a better way to handle sensitive information by doing exactly what we said earlier in this post. I think it is becoming more clear to you that we should prefer Cookies to exchange sensitive data with the server over storing the server’s response on the local/session storage.

On the other hand, Cookies are very size-limited, and if we need to save things like user preferences or any other data we need, we should go with local/session storage.

Final considerations

We have reached the end. I hope this post has clarified the difference between LocalStorage and Cookie. They’re not the only way to store data in the browsers, and after all, they’re not concurrent because both have their use case.

Check these links to have further details about Cookies and Web Storage API. We also have a YouTube video that can be very helpful. In addittion, you can check these links below.

We want to work with you. Check out our "What We Do" section!