Introduction to HTML LocalStorage API

Web apps can store data locally within the user’s browser instead of storing data in cookies.  LocalStorage is per origin so all pages from an origin can store and access the same data.

The LocalStorage API is used to store key value pairs of data, It also only stores strings, so all data must be converted to strings.


The methods of the LocalStorage API are:


The setItem method is used to store a key and its associated value into local storage, if any existing data with the same key exists, it gets overridden with the new value.


localStorage.setItem(key, value);


The getItem method is used to retrieve the value associated with a key from local storage, if there is no value associated with the provided key, it returns null.


localStorage.getItem(key); // returns value associated with key.


The removeItem method is used to remove the value associated with a key stored in local storage.


localStorage.removeItem(key); // removes value associated with key.


The clear method is used to remove all data stored in local storage


localStorage.clear(); // all data in localstorage is removed, localstorage is now empty.

Common Pitfalls

getItem Always returns value as a string

All data stored in localstorage is stored as strings, data of other types are implicitly converted to strings before being stored.

So if you store a boolean or an int or anything other than a string, you will get back a string when you get it


var a = true; //a is a boolean
var b = 10; //b is an int
var c; //c is undefined


localStorage.getItem('a'); //returns string 'true'
localStorage.getItem('b'); //returns string '10'
localStorage.getItem('c'); //returns string 'undefined'

Storing Objects

Since localStorage only works with strings, you have to stringify  and parse objects to use them with localStorage


var obj = {"favorite-color":blue}
localStorage.setItem(obj, JSON.stringify(obj));
obj = JSON.parse(localStorage.getItem(obj));

Browser Quirks

localStorage is supported in almost all browsers, you can find the full list here. But some browsers have some quirks like some versions of iOS store localStorage data in a location that may occasionally be cleared out by the OS.

IE11 does not properly synchronize localStorage between different windows

Browsers also set limits (usually 10 Mb) on how much data you can store in localStorage.

Share this!

Leave a Reply

Your email address will not be published. Required fields are marked *