Skip to main content

Cookies vs Local Storage vs Session Storage

 

Why should we store data in the browser?

One of the key reasons to store data in the browser is performance. You can’t always wait for the server to send a response for every request. Sometimes it’s better to have some piece of information stored in your browser for quicker access. So basically, there are 3 ways to store data locally in the browser — Cookies, Local Storage and Session Storage.

Cookies

Cookies are the oldest and most common way of storing data. A cookie is basically some text-based information. It is usually set by a server, nevertheless it can also be set in the browser. The working is simple, each time a request is made from the browser, the browser automatically attaches the cookie along with it. Now the server receives the information that was set in the browser.

We can set an expiration time for the cookie that is being set. There’s only 4KB storage space allowed for the entire cookie data. Cookies are advantageous as they work in older browsers as well. A cookie can be accessible to every window in the browser.

If you want to set a cookie manually using your browser, you can type this piece of code in your browser dev console where  is the key and  is the value and then have a look at your Applications tab under Cookies to check if it set or not.

Cookie set in browser
Cookie being set

Common Use Cases

  • Authenticating logged in users — Whenever the user successfully signs in, the server sends a success response and also sets a cookie, so that whenever requests are sent in the future, the server recognizes that the user is signed in.
  • Identifying user state — For example in an e-commerce site, whenever the user adds a new item and refreshes the page, it automatically shows up the added item in the cart, with the help of cookies.

Web Storage

In HTML5 Web Storage such as Local Storage and Session storage were introduced. So, what has changed? The idea behind introducing these is to make storing and retrieving values easier on the client side. The data in these storages are generally stored in key-value pairs. One particular improvement was that the size of the storage was much better than cookies.

You can access the Web Storage values using Javascript. None of this data can be read by the server unlike the cookies, unless we manually pass them along with the request. In other words, you can consider this Web Storage as your small personal database present in your browser.

Local Storage and Session Storage have a lot of things in common, with only a few dissimilarities. Let’s have a look at both:

Local Storage

The Local Storage is a type of Web storage which like cookies is accessible on all windows in the browser. When it comes to the storage capacity, it can store upto 5–10 MB, which is much better when compared to cookies. And the values set in local storage never expires until and unless we manually remove them.

On your browser console use these commands to set, get, remove and clear Local Storage values.

Session Storage

The Session Storage has a lot of similarities to Local Storage, but the storage size is limited to 5MB. Also, the values stored gets automatically removed from the browser when you close the active tab. As the name suggests, the values are only available for that session.

On your browser console use these commands to set, get, remove and clear Session Storage values.

Image for post
Values set using local storage

Common Use Cases

  • An application’s light mode/dark mode can be stored here in the browser.
  • Likewise you can store the web application’s user customized data here. Say, choosing themes, layouts, etc.

Which one should you choose?

The answer to this depends on what is your exact use case. If you want your page to always hold some data that is not confidential, then you can use . If the server needs to know some information like authentication key, you should use cookies to store them.  can be used to store the state of interface, i.e., whenever you visit a page, customize it, visit another page and return to the same page, you would want to show the page how the user customized it. That’s a good use case for .

Conclusion

By now, I believe you know how each of these storages work and how they differ. I hope you’ll be putting this knowledge to use, when you are building your own application.

Thanks for reading! Happy coding!

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...