Store data

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.

  • Cookies are send to the server with every request, in the HTTP headers. 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 running 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.

Cookies

Accessibility of data across your website

The local storage object isn't just available everywhere on your website. It's specific to the origin of the page and 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 or hosts (e.g. www or no-www) on your website. You can't access the data stored from the other origins.

Here's a example of whether a page is following the same-origin policy for the fictive URL https://spicyyoghurt.com/tutorial1:

  • Same origin - https://spicyyoghurt.com/tutorial2
  • Same origin - https://spicyyoghurt.com/javascript-tutorials/tutorial1
  • Different protocol - http://spicyyoghurt.com/javascript-tutorials/tutorial2
  • Different host - https://www.spicyyoghurt.com/tutorial1
  • Different port - https://spicyyoghurt.com:81/javascript-tutorials/tutorial3

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.


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

Let's put it to the test and eat a cookie

This little example demonstrates the use of storing data on the client side. You start out with a whole cookie and you can click the eat button to take a bite.

A freshly baked cookie A cookie with a bite out
Eat cookie
Bake cookie

The state of your cookie will be stored in the localStorage. So if you refresh the browser the cookie will still be eaten.

To reset the state of the cookie you can press the bake button. You cookie will be whole again! If you like you can even try to clear your browser cache to do the same. When there is no data on the client the cookie is reverted to its default state (a whole cookie).

Storing other data types, like numbers and booleans

The localStorage can only store strings for each key. Any other data type, like numbers or booleans, need to get converted manually.

Here's an example of how to store numbers and booleans in the storage:


            let myNumber = 12345;
            localStorage.setItem('myNumber', myNumber.toString());

            let myBoolean = true;
            localStorage.setItem('myBoolean', myBoolean.toString());
        

When extracting the data you'll need to convert back from string to the chosen data type. In the example, booleans are stored as false or true. You could also store it as a 0 or 1. It doesn't matter, as long as you read and write following the same format.

Here's an example where the data is converted back to it's original datatype:


            let myNumber = Number(localStorage.getItem('myNumber'));
            let myBoolean = localStorage.getItem('myBoolean') == 'true';
        

How to store entire JavaScript objects?

Let's say you don't just want to store a simple value, but want to save an entire JavaScript object, like the one in the next example. How are you going to fit it in the local storage?


        let myObject = {
                value1:'one',
                value2:'two',
                value3:'three'
                }
        

All data items in the local storage are stored as key value pairs, where the values are strings. So if you want to store an entire JavaScript object you'll have to flatten the object and 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:


        let 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:


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

Try local storage in practice

Create your own HTML5 game

A browser game is a great case to apply local storage. You can store the progress of the player on the client. Check out this tutorial series to learn how to create your own game in HTML5 and JavaScript.

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') !== null{
            //Data item exists
        }else{
            //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
            }else{
                //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:



            let nextValue;
            for (let 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. If the key doesn't exist, nothing will happen.


                localStorage.removeItem('myKey');
                

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.


                localStorage.clear();
                

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. If storing data forever isn't what you're looking for, you can store data per session.

Lifetime of local storage data

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:


            let 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.

Conclusion

The localStorage holds many advantages over storing data in cookies. It's available everywhere in your application and offers ways to add, find and delete data. You can even use it to store entire JavaScript objects. The data is stored indefinitely until you clear the browser cache.

If you have any more questions about using the localStorage, you can ask them in the comments below.

Leave a comment