HTML5’s storage: localStorage & sessionStorage

Lately the need to store data on the clientside has been constantly growing with modern apps like Gmail and Google Wave, not only to speed things up and reducing network traffic but also to allow web applications to work offline. Until HTML5 we were limited to cookies and Google Gears.

But cookies are not sufficient anymore, they permit a maximum storage of 4KB and are sent to the server with every request from the client.

Introduced in HTML5 localStorage and sessionStorage are a part of the Web Storage specification.

So HTML5 introduced a Web Storage spec comprised of three technologies: Local Storage,Session Storage and Database Storage.

We’ll discuss localStorage and sessionStorage and maybe in a future article the sql database storage.

Localstorage is somewhat similar to sessionstorage but it is persistent between browser sessions. With session storage if you close the browser window the data contained in it will be deleted. Local storage is also available between browser windows.

Localstorage and Session storage cand store data in the key:value format, and can only store strings. So if you store any other type of data that Javascript allows(integers, floats, booleans,) when you read it you must convert it from string. The max size of the objects are 5mb and currently they cannot be extended to a bigger size.

Let’s write some javascript that will read/write from the localStorage

You can use the API for working with localStorage like this:

localStorage.setItem('item', 'value') //sets item:value
localStorage.getItem('item') // returns 'value'
localStorage.key(0) // returns 'value'
localStorage.removeItem('item') // removes 'item'
localStorage.clear() // clears local storage for this domain

or if it’s more convenient to you you can treat localStorage like a normal Javascript object:

localStorage.item = 'value'
localStorage.item //outputs 'value'
localStorage['item'] //outputs 'value'
delete localStorage['item'] //deletes the value

Security issues with localStorage

I advise against storing important Information in the local storage as it can easily be retrieved and read by an XSS atack. You should also keep your SessionId stored in cookies and use the HTTPOnly and Secure flags.


localStorage and sessionStorage are available right now in the latest versions of Safari, Firefox, Opera and in IE8+. PPK has a nice comparison table that also includes storage events. For more compatibility data visit this website.

To learn more about the storage event visit PPK’s site and it would be a good idea to skim through the Storage spec.

Tagged with: