Often, web developers need to store data pertaining to the present web page displayed on web browser. Typically, they rely on browser cookies for this purpose. But it has certain limitations such as size limit of 4kb. HTML 5 provides you a couple of simple ways to easily store and retrieve data on your web page – LocalStorage and SessionStorage APIs. You can not only store simple data such as numbers & strings but also complex data types such as JavaScript objects in them. In this article, we will learn how to store objects in HTML5 Local Storage/Session Storage.
What is HTML5 Web Storage
These days websites and applications have become very data intensive and web developers need to often store data on client web browsers. Earlier people used HTML cookies for this purpose. But cookies can store data only up to 4kb space. If you want to store larger data such as JSON response, table data, etc. you need to use Web storage API provided by web browsers.
It is more secure than passing data over cookies, allows you to store large amounts of data (up to 5Mb) and offers better performance. These data are stored as key-value pairs making it easy to store, modify and access page data, as compared to cookie values. Both key as well as value should be strings. The web browser will maintain a separate list of key-value pairs for each origin-protocol combination.
Web storage is organized per origin and protocol. So you can store data for an origin and protocol at one place, allowing all pages from that origin to access the data. It offers two types of storage – Local storage and Session storage.
Types of Web Storage
There are two types of web storage supported by HTML5 web browsers – Local Storage and Session Storage.
Local Storage
Local storage allows you to store data locally on web browser, with no expiration date. It will continue to remain even when the web browser is closed and re-opened later. This local storage can be accessed on any window or tab. As mentioned earlier, browser will maintain different list of key-value pairs for each domain-protocol combination. Key-value pairs of one domain-protocol will not be accessible from another domain-protocol. When you open a website, you can only access local storage of that domain and not any other domain. The Local Storage allows you to save client data as key-value pair, modify as well as retrieve it using keys.
Session Storage
Session storage is similar to local storage, except that it automatically gets deleted at the end of browser session. In other words, its data is accessible only as long as the browser tab remains open. Like Local Storage, web browser maintains a separate list of key-value pairs for each domain-protocol combination. Here too, key-value pairs of one domain-protocol will not be accessible from another domain-protocol. When you open a website, you can only access session storage of that domain and not any other domain. The Session Storage allows you to save client data as key-value pair, modify as well as retrieve it using keys.
How to Store Objects in HTML5 Local Storage/Session Storage
Now that we have a basic understanding of how web storage works, let us learn how to use them.
How to Store Objects in HTML5 Local Storage
Let us learn how to add data to LocalStorage, how to retrieve and remove it. In all cases, we will refer to the global localStorage object that is available by default on all pages of web browser that supports Local Storage API.
Add Objects to Local Storage
There are two ways to add data to local storage – using setItem() function as well as using localStorage.key=value notation. We will look at both of them. Here is how to add two data – for company name and location.
localStorage.setItem("name","ABC Company");
localStorage.setItem("location","New York");
In the above code, we need to supply 2 arguments to setItem() function – name of the key and value of the key. In the above example, name is the key and ‘ABC Company’ is the value.
We can do the same thing also as shown below.
localStorage.name = 'ABC Company';
localStorage.location = 'New York';
The above code will create two key-value pairs for the domain-protocol where it is executed. We need to assign the value to localStorage.key variable.
You can also use the above functions to modify existing key value pairs. Here is an example to modify the above values. If you use names of existing keys, it will overwrite their existing values.
localStorage.setItem("name","XYZ Company");
localStorage.setItem("location","NYC");
localStorage.name = 'XYZ Company';
localStorage.location = 'NYC';
Check Local Storage
On the other hand, you can access or retrieve the value of a key in localStorage using getItem() function or using localStorage.key variable.
Here is how to get the value using getItem() function.
localStorage.getItem('name');
The above code will return the value of the key name, if present. Else it will return undefined. You can directly use this value in other JS code.
console.log(localStorage.getItem('name'));
You can also access these values using localStorage.key variable. Here is an example to get value of name key.
localStorage.name;
Here is how to use it other code.
console.log(localStorage.name);
If you want to find out the total number of key value pairs stored in localStorage API of a given domain, use localStorage.length variable.
Remove Local Storage
Lastly, you can remove one or more keys from localStorage object using removeItem() function. Here is an example to remove keys name and location.
localStorage.removeItem('name');
localStorage.removeItem('location');
The above code will remove keys one by one. Please note, if the specified key is not present in local storage, the web browser will silently continue with execution. It will not give any warning or error messages.
If you want to remove all keys for a given domain-protocol combination, you can use localStorage.clear().
localStorage.clear();
Please note, if you try to reset the value of a key using setItem() function to ” or null or undefined, the key-value pair will continue to exist, with null string. When you use removeItem(), the key-value pair itself is removed.
Here is a sample code snippet that first checks if local storage is supported. Then it stores data in it, then it retrieves and displays the stored value.
if(window.localStorage){
localStorage.setItem("name","PQR company");
var name=localStorage.getItem("name");
alert("Company name is " + name);
localStorage.removeItem("name");
}
else{
alert("local storage not supported")
}
How to Store Objects in Session Storage
Just as local storage, you can also store session-specific data in Session Storage. It will be automatically deleted at the end of session. It cannot be accessed from another browser tab. But it will still be accessible on page refresh or reload.
Add Session Storage
There are two ways to store data in sessionStorage object – using setItem() function and using sessionStorage.key=value notation.
Here is how to add company name and location in sessionStorage.
sessionStorage.setItem("name","ABC Company");
sessionStorage.setItem("location","New York");
Here also, we need to supply two arguments – key and its value. In the above code, name is the key and ‘ABC Company’ is the value.
You can also assign the values to keys as shown below.
sessionStorage.name = 'ABC Company';
sessionStorage.location = 'New York';
Both these code snippets will create 2 key-value pairs for the given session for the domain-protocol where they are executed.
If these keys already exist, and you run these code, then their values will be overwritten. In other words, you can also use setItem() or sessionStorage.key to modify values.
sessionStorage.setItem("name","XYZ Company");
sessionStorage.setItem("location","NYC");
sessionStorage.name = 'XYZ Company';
sessionStorage.location = 'NYC';
Check Session Storage
Just as in the case of localStorage API, you can access the stored keys using getItem() function or as sessionStorage.key variable.
Here is an example to retrieve key name’s value using getItem().
console.log(sessionStorage.getItem('name')); // output is ABC Company
If the specified key is not present in sessionStorage, it will return undefined value.
console.log(sessionStorage.getItem('city')); // output is undefined
You can also directly access keys using sessionStorage.key.
console.log(sessionStorage.name); // output is ABC Company
If you want to find out how many key-value pairs are store in session storage, you can use its length property.
console.log(sessionStorage.length); // output is 2
Remove Session Storage
Lastly, you can remove any key value using removeItem().
Here is an example to remove keys name and location.
sessionStorage.removeItem('name');
sessionStorage.removeItem('location');
If the specified keys are not present in sessionStorage, then it will silently continue with execution. It will not throw any error or warnings.
If you want to delete all key-value pairs for this domain-protocol’s session, then you can call clear() function.
localStorage.clear();
Here also, if you try to reset the value of a key-value pair using setItem() function to empty quotes or null or undefined, the key-value pair will continue to exist, with null string. But when you use removeItem() function, the key-value pair itself will be removed.
Here is an example where we first check if session storage exists. If so, we add a data to it, then we retrieve this stored value, and finally remove it.
if(window.sessionStorage){
sessionStorage.setItem("name","PQR company");
var name=sessionStorage.getItem("name");
alert("Company name is " + name);
sessionStorage.removeItem("name");
}
else{
alert("session storage not supported")
}
Local Storage vs Session Storage
Here is a quick summary of the key differences between local and session storage.
Local Storage | Session Storage |
Storage of up to 5Mb per domain | Storage of up to 5Mb per domain |
No expiry date for data | Data expires at the end of session |
Can be accessed from other tabs | Can be accessed on same tab only |
Supported by HTML 5 browsers only | Supported by HTML5 browsers only |
Check Browser Support for Web Storage
Although web storage is supported by most modern web browsers such as Chrome, Edge, Firefox, Opera, etc. it is always good to check first before you store data. window.localStorage object will be non-null value in web browsers that support Local Storage. Else it will be undefined. Similarly, window.SessionStorage object will have non-null value if SessionStorage is supported. Else it will be false. Here is the code to check if Local Storage is present on your web browser.
if(window.localStorage)
{
alert("Local storage supported")
}
else
{
alert("Local storage not supported")
}
Here is the code to check if Session Storage is supported or not.
if(window.sessionStorage)
{
alert("Session storage supported")
}
else
{
alert("Session storage not supported")
}
If you want to check for both local as well as session storage with a single code, you can do it as shown.
if (typeof(Storage) !== "undefined") {
alert('Web storage supported');
} else {
alert('Web storage not supported');
}
Conclusion
In this article, we have learnt how you can store objects in HTML5 local storage / session storage using HTML5 Web storage API. In it, we also learnt how Local Storage and Session Storage work. We learnt how to add data to local storage and session storage, how to retrieve these values and also how to remove them. You can use any of these storages, depending on your requirement. Please note, while using web storage, it is better to avoid using whitespace characters in key names and also avoid starting the key name with numbers.
FAQ
1. When to use Local Storage?
Local storage is useful if you want to retain data on client browser for long time, and make it accessible across multiple tabs
2. When to use Session Storage?
Session Storage is useful if you only want to store session-specific data that you want to retain till end of session and want to auto delete them when session ends. It is also useful if you want to retain data across page refresh or reload.
Also read:
How to Remove Duplicate Values from JS Array
How to Disable Browser Autocomplete and Autofill
Difference Between Let and Var in JavaScript
Sreeram Sreenivasan is the Founder of Ubiq. He has helped many Fortune 500 companies in the areas of BI & software development.