Thought leadership from the most innovative tech companies, all in one place.

Everything you need to know about HTML5 local storage and session storage

Understand it by building actual practical applications

Photo by Caspar Camille Rubin on Unsplash

Photo by Caspar Camille Rubin on Unsplash

You probably have heard of local storage or session storage terms but never got a chance to explore it. This article will clear all your concepts about it.

Local and Session storage comes under the category of HTML5 Web Storage.

It's not the same as session storage that you might be familiar with if you came from a Java background where the session is stored on the server-side.

We will use the term Web Storage when we talk about Session and Local Storage together.

Web Storage is used for storing data on the client-side. So the data will be available even when the page is refreshed.

Previously before Web Storage came into play, the only way of storing the data on the client-side was using cookies.

Cookies are still used but there are some disadvantages of using them, such as:

  1. Cookies are stored on the client-side and are transferred to the server on every request sent to the server. This makes cookies less secure.

  2. Cookies have a storage limit. We can't store more data into cookies after a certain limit.

  3. Cookies can be disabled by using some browser extension tools.

  4. Storing data in cookies required some extra code.

So Let's Explore Web Storage Now

Session Storage:

  1. Session Storage is for per browser tab. So data stored in one browser tab will not be accessible in another tab.

  2. Each browser tab has separate session storage data.

  3. Session Storage data gets cleared when we close the tab.

  4. It also gets cleared when we close the browser.

Local Storage:

  1. Local Storage is used for storing data across the entire application

  2. Data stored in local storage will be accessible across all the tabs or pages only for that domain ( like www.google.com, www.medium.com, etc.).

  3. Local Storage data stored for a particular domain will be accessible even you open another browser window (Control + n or Command + n (Mac)) on the same browser.

  4. Local Storage data stored on normal browsing sessions will not be available when you open a browser in private browsing or in Incognito mode.

  5. Local Storage data will not get cleared even if you close the browser. Because it's stored on your browser cache in your machine.

  6. Local Storage data will only be cleared when you clear the browser cache using Control + Shift + Delete or Command + Shift + Delete (Mac).

  7. We can also clear the local storage data programmatically. We will see how to do that soon.

Both Local and Session Storage have a storage limit of 5MB each.

All modern browsers support Web Storage. Regarding internet explorer, it's supported from IE version 8 and above.

You can check your browser storage limit by visiting http://dev-test.nemikor.com/web-storage/support-test/ and running a web storage test.

That's enough for the details. Now let's dive into how to use it

Both Local and Session Storage has the same syntax:

Add data to Local Storage

localStorage.setItem(key, value)

Remove data from Local Storage

localStorage.removeItem(key)

Add data to Session Storage

sessionStorage.setItem(key, value)

Remove data from Session Storage

sessionStorage.removeItem(key)

Both the key and value has to be a string. But we can store the JSON object also by using JSON.stringify method.

Local Storage:

Let's check out a simple todo list application using React just to understand the web storage concepts.

Check out the live demo of the todo list HERE.

Github Source Code: https://github.com/myogeshchavan97/todo_list

It's not a complete application with all todo list features. I just built it for this demo. Try adding some todos in the application, you will see something like this:

Todo List App

Todo List App

Now if you refresh the page, all the todos will be lost and you have to enter it again.

To fix it, we will add the localStorage functionality here to retain the todos even when we access the application in any tab. As you can see in TodoList.js inside components directory, todos is an array declared in the state as:

state = {
  todos: []
}

To save it to localStorage we need to convert it to a string by using JSON.stringify because local and session storage allows storing only strings.

We will do that as shown below:

const { todos } = this.state;
const json = JSON.stringify(todos);
localStorage.setItem("todos", json);

Now if we print the saved data, you will see the output as seen below:

Todo local Storage

Todo local Storage

To read the data back, we need to parse it because it's stored as a JSON string

const todos = localStorage.getItem("todos");
if(todos) {
 const parsedJSON = JSON.parse(todos);
 this.setState({ todos: parsedJSON });
}

The complete code will look like this:

Demo: https://codesandbox.io/s/github/myogeshchavan97/todo_list_with_localstorage

Let's understand the above code from componentDidMount and componentDidUpdate.

  1. Whenever we add the item to todo, the state todos array changes so this is the perfect time to store the todos in local storage.

  2. We are doing that in componentDidUpdate method. This method gets called when a state or props are changed. In this method, we are checking if the previous todos array and current todos array length is different and only then store in local storage

  3. In componentDidMount, we are reading from the localStorage and adding back to the state.

So every time the component is rendered we are reading from localStorage.

This will make sure that the todos are not lost even if we refresh the page.

Github Updated Source Code: https://github.com/myogeshchavan97/todo_list_with_localstorage

Another use case where Local Storage is used is for storing shopping cart items where items added to cart does not get lost even after a page refresh.

Session Storage: Goto any website like medium.com and in the console paste the following line and hit enter.

sessionStorage.setItem("name", "Advanced User")

Now, a new entry will be added in sessionStorage for the medium.com domain.

Now, If you check the value using sessionStorage.getItem("name"), you will see the text "Advanced User" which we set as shown below:

Session Storage Example

Session Storage Example

Now open medium.com in another tab in the same browser window and check the value of sessionStorage.getItem("name").

You will see null printed instead of "Advanced User" as shown below:

Session Storage in new tab

Session Storage in new tab

This is because each tab has separate Session Storage data even on the same domain but local storage data is available across the same domain for each new tab.

You can see all the local and session storage data for each site under the Application tab in Chrome Developer Tools as shown below:

Web Storage Data

Web Storage Data

So the point to remember is that, you use session storage only when you want to persist data in a single tab and session storage data gets cleared when tab is closed or browser is closed

Now consider the following scenario.

Suppose, you have a modal on the page that displays some long form to enter details. Many times it happens that, the user enters some data in the form, and by mistake clicks outside the modal and the modal gets closed. Because of which he loses all the entered data.

To avoid the loss of data, we can use sessionStorage so the stored data in modal will only be applicable to the current tab.

Demo: https://codepen.io/myogeshchavan97/pen/rNaBONm

Here we have a button for opening the modal. When we click on the close button inside the modal, we are saving all the entered data in sessionStorage and when the user opens the modal again, We fill out the input fields with previously entered values.

Also, note that we are clearing the session data on page load so, on the initial load, the form will be empty.

To put together,

Github Source Code for all applications we built:

  1. https://github.com/myogeshchavan97/todo_list
  2. https://github.com/myogeshchavan97/todo_list_with_localstorage

Codepen Source Code: https://codepen.io/myogeshchavan97/pen/rNaBONm

That's it for today. I hope you learned something new today.




Continue Learning