The open blogging platform. Say no to algorithms and paywalls.

3 Ways To Store Data in the Browser

Cookies, local storage, and session storage

Sometimes, it is better to access data from the browser rather than sending requests to the server. The 3 ways to store data in the browser are Cookies, Local Storage, and Session Storage. Depending on the needs any one of them is used to store data in the browser.

In today's article, we will discuss an in-depth comparison between local storage, session storage, and cookies. Let's get started.

Cookies vs Local Storage vs Session Storage

To have a basic understanding of the similarities and the differences between them, see the chart below:

image

Cookies vs local storage vs session storage | Reference

So there are some similarities and also some differences between the three. Local storage and sessions storage have more similarities and they are comparably new. Cookie is the oldest among them and different in many ways than the other two.

All three of them are browser-independent. That means if some data is stored in one browser, it will not be stored in a different browser on the same machine. For example, the data stored in Google Chrome will not be stored in Firefox on the same computer.

Also, different users do not share cookies or local storage between them. So if some data is set for one user, none of the other users will be able to see that.

If you open the developer tool from your browser and go to the "Application" section, you will be able to see the 3 types of storage.

image

3 types of storage from the browser | Screen captured by the author

Now let's talk about each one of them individually.

Cookies

Cookies are the oldest way of storing data in the browser. It is available in both HTML4 and HTML5. Cookies are basically some text-based data with a name-value pair. Cookies can only store 4 KB of data which is much smaller than local storage and session storage.

Cookies are a convenient way to carry data from one session to another on a website. It can be used for authentication purposes and also for identifying the state of a user. For example ---

  • When a user logs in to a website, the server sets a cookie. So the server can recognize that the user is logged in for other sessions.
  • When shopping from an e-commerce website, if a user adds an item to the cart, usually a cookie is set. So if the user refreshes the page the item will still be in the cart list, and the user can add more items from this state.

Access cookies with JavaScript

We can access cookies from the browser using document.cookie property. The value of document.cookie consists of name=value pairs. See the following example.

document.cookie = 'name1=value1'

The above expression will update a cookie named 'name1' with the value 'value1'.

You can see the cookie added to the browser by inspecting the page.

image

One document.cookie= expression can add one cookie. Let's add two more cookies.

document.cookie = 'name2=value2'\
document.cookie = 'name3=value3'

image

Now putting document.cookie will show all three of the cookies.

image

You can also raise an alert by using alert(document.cookie).

image

Local Storage

Depending on the browser, local storage has a capacity of 5-10 MB. It was introduced in HTML5. Local storage stores data only in the browser and never expires unless manually removed. Local storage can be accessed from any window. That means if a user closes the browser local storage will be saved next time the user opens it again.

Access local storage with JavaScript

You can access local storage by using the localStorage property. Local storages are string values with key-value pairs. See the example below.

localStorage.setItem('key1', 'val1');\
localStorage.setItem('key2', 'val2');\
localStorage.setItem('key3', 'val3');

Three items in the local storage are added.

image

setItem() method sets the values for local storage. The getItem() method will get items from local storage. You need to put the key inside getItem() to get a value. Using console.log() you can then print the values.

console.log(localStorage.getItem('key1'));\
console.log(localStorage.getItem('key2'));\
console.log(localStorage.getItem('key3'));

image

localStorage.clear() will clear the entire local storage.

To remove one item you can use localStorage.remove(). Again you need to put the key inside the method.

localStorage.removeItem('key1');

After removing value1 console.log(localStorage.getItem('key1')); will return null.

You can also save an array to local storage.

_let_ arr = ['val1', 'val2', 'val3'];\
localStorage.setItem('keys', arr);

The array arr will be stored in the local storage. But the whole array will be stored as a string. To solve this problem you can use [JSON.stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) and [JSON.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).

_let_ arr = ['val1', 'val2', 'val3'];\
localStorage.setItem('keys', JSON.stringify(arr));\
x = JSON.parse(localStorage.getItem('keys'));\
console.log(x);

Now this will be stored as a JavaScript object.

image

So there are four main operations in local storage:

localStorage.setItem();\
localStorage.getItem();\
localStorage.removeItem();\
localStorage.clear();

Session Storage

Session storage is mostly similar to local storage. The only difference is session storage will be deleted after a session. That means if you save something in session storage and close your browser you will not be able to see the data after you open the browser again. Session storage has a capacity of 5 MB.

Access session storage with JavaScript

All the operations described in local storage are also valid for session storage. To access session storage you need to use the sessionStorage property. Others are pretty much the same as local storage.

To add data to session storage you will use sessionStorage.setItem() with a key-value pair.

sessionStorage.setItem('key1', 'val1');

image

Note: IsThisFirstTime_Log_From_LiveServer is there because I was using the live server extension from VS Code.

As you can see val1 is added to the session storage. sessionStorage.getItem()sessionStorage.removeItem(), and sessionStorage.clear() will work exactly the same as local storage.

If you close the browser tab the session storage will be gone.

Local storage and session storage together can be referred to as web storage. Web storage is used to save data for quick access. Like users custom data. For example ---

  • Suppose a website has light/dark mode. If a user sets the dark mode in the browser, the data can be stored in local storage. The data is saved in local storage for this user only. This way when the user opens the website from the browser again, dark mode will be enabled automatically.

Choose What To Use When

So how can you choose between the three? It depends on your needs. If you need some data to be stored in the browser and always hold that data for a user, you will use local storage. On the other hand, if you want to erase the data after every session, you will use session storage. If the server needs some data like an authentication key, you will use cookies.

So the use case depends on the need.

That's it for today. I hope you got a good grasp on cookies, local storage, and session storage from this article. Thanks for reading!




Continue Learning