Spicy Yoghurt | Last updated: 22 April 2019 | JavaScript tutorial

Store data with HTML5 local storage

Use the HTML5 local storage to store and read data in the browser. Learn how to store entire objects and how to manipulate data in the storage object. Follow this tutorial to learn all about storing client-side data with JavaScript.

What is HTML5 local storage?

With the HTML5 local storage property, you can store and read data in the browser. It is part of the HTML5 Web Storage API. You can store at least 5MB of data per origin (more on some browsers and devices) and access it from all pages, client-side. The data is accessible across all browser tabs and will still be there after the window has closed and even after closing the browser. It will persist until explicitly deleted.

Local storage is ideal for storing non-critical data client-side. It is easy to use and easy to set-up. You can use it for simple website settings, online tools and even to store progress in web games. Just remember that users can clear the local storage by clearing the browser cache. So important data still needs to be stored somewhere off the client.

Local storage vs cookies

Often, when people think about storing data for a web page, cookies come to mind. There are some big differences between cookies and the local storage.
  • Local storage is only available client-side. Cookies are normally read server-side.
  • Cookies are send to the server with every request, in the HTTP header. Local storage is not. So it doesn't effect your website performance.
  • Max cookie size is about 4KB, local storage has room for at least 5MB of data. (Depending on the browser and device the page is run on)
  • The Storage object offers a nice set of functions to easily manipulate the local storage. Cookies are stored as one long string and you'll need to implement your own way of dealing with data in a smart and structured way.
Basically, if you need to access data on the client-side, local storage is the way to go. It holds many advantages over using the old fashioned cookie.

Store and read data

Let's get to the more practical part of this tutorial and actually use the local storage. To manipulate data in the local storage, first get the read-only Storage object from the window.localStorage property. You can access it anywhere in your JavaScript code like this:

        var localStorage = window.localStorage;
With this reference you can start using the local storage to access and read data.

To store data in the local storage, simply use the setItem() function on the Storage object and pass a key and value. Using a new key will create a new data item, using an existing key will update the previous value.

            localStorage.setItem('myKey', 'myValue');
You can retrieve the item again by calling getItem() on the Storage object and passing the key as an argument. The function will return the value matching the key. If the item doesn't exists, the function will return null.

             var myValue = localStorage.getItem('myKey');

How to store entire JavaScript objects?

All data items in the local storage are stored as strings. So, if you want to store a JavaScript object you'll have to turn it into a string too. That's why you need to stringify the object first. You can use JSON.stringify() to convert a JavaScript object into a savable string.

Here's an example of a simple object getting stored in the local storage:

        var myObject = {value1:'one', value2:'two', value3:'three'}
        localStorage.setItem('myObject', JSON.stringify(myObject));
You can retrieve the data as you would normally, only this time you'll have to put the object back together. The data is retrieved as string and needs to be parsed into an object again. You can use JSON.parse() to do this. Request the value and parse the string to get the JavaScript object back.

In the next example the JavaScript object is read from local storage and stored into a variable after being parsed:

        var myObject = JSON.parse(localStorage.getItem('myObject'));

How to check if a key exists?

Sometimes you'll want to know if a key in the local storage already exists. You can check if a data item exists in the local storage by calling getItem() and pass the name of the key as argument. The function will return null if the item doesn't exist.

Here's a practical example in which a key is checked for existence:

        if (localStorage.getItem('myKey'){
            //Data item exists
            //Data item doesn't exist,

Check if local storage is used or empty

You can also check if the local storage contains any items at all by using the length property on the Storage object. A length of 0 indicates an empty storage. Anything above that indicates the local storage is in use.

            if (localStorage.length > 0){
                //Items are stored in local storage
                //Local storage is empty

Loop over all keys in the storage

Sometimes you want to read the data items in the local storage but you don't know the exact keys. You can still get the key name by use the key() method. It accepts an index as argument and returns the name of the key matching the index. Combine it with the length property on the Storage object to create a loop. This way you can loop over all data items in the local storage and read data without knowing the exact keys. Here's an example:

            var nextValue;
            for (var i = 0; i < localStorage.length; i++){
                nextValue = localStorage.getItem(localStorage.key(i));
                //Do something with nextValue..

Clear the local storage

If you want to remove items from the local storage, you can use removeItem() to delete a single item. You can call it and pass a key as argument.

When that's not enough and you want to clear the entire local storage, use the clear() function. It clears all data in the local storage, leaving the object completely empty.


Lifetime of local storage

The Storage object in the localStorage property has no expiration date. This means it will stay available even after the browser closes. You can retrieve the data endlessly after storing it, even after months or even years have passed. The only way the data can be cleared is by deleting it explicitly via Javascript or by clearing the browser cache. The lifetime of data in the HMTL5 local storage

Store data per session

If you don't want to store data for so long, but still want to store data client-side, then there is the sessionStorage property. It behaves the same as localStorage, only it expires the moment the window closes. Also, the data is stored per browser tab, not per domain.

You can access the sessionStorage property on the window like this:

            var sessionStorage = window.sessionStorage;
sessionStorage also contains a Storage object. So, you can use all previously mentioned methods, just like you would with the localStorage. Only this time the data is stored much less permanent.

Local storage for http and https version of your website

The local storage object is specific to the origin of the page. It follows the same-origin policy. Each protocol/domain/port combination has its own local storage object. So the http version of your website has a different local storage object than the https version. The same is true for using different ports on your website. You can't access the data stored from the other origins.

Here's a practical example of whether a page is following the same-origin policy:
  • Same origin - https://spicyyoghurt.com/tutorial1
  • Same origin - https://spicyyoghurt.com/javascript-tutorials/tutorial1
  • Different protocol - http://spicyyoghurt.com/javascript-tutorials/tutorial2
  • Different port - https://spicyyoghurt.com:81/javascript-tutorials/tutorial3

Leave a comment