Web storage API

What it is

Originally part of the Web Applications specification, but now covered by its own (a candidate recommendation since 8 December 2011), the W3C’s Web Storage specification defines an “API for persistent data storage of key-value pair data in Web clients.” In other words, it’s a replacement for and improvement on the only local storage previously available to web applications: cookies.

The Storage interface defines a few simple methods (it should be obvious how most work just by their name) that permit JavaScript to get and set key-value pairs:

  • .setItem(key, value)
  • .getItem(key)
  • .removeItem(key)
  • .clear()
  • .key(index)
  • .length

The Storage interface has been implemented as two objects: local and session. Both share the same API, but the localStorage object shares data across windows and tabs and persists the data, while the sessionStorage object is tied to a single window or tab and is lost when the window or tab is closed.

Sources: Web Storage. W3C Candidate Recommendation 8 December 2011, HTML5 Doctor

Where it can be used

  • Chrome 4.0+
  • Firefox 3.5+
  • Internet Explorer 8.0+
  • Opera 10.5+
  • Safari 4.0+
  • Android 2.0+
  • iPhone 2.0+
  • Opera Mobile 11.0+

Sources: When can I use…, Dive Into HTML5

How to detect it

Local storage

try {
  return 'localStorage' in window && window['localStorage'] !== null;
} catch(e) {
  return false;

Session storage

try {
  return 'sessionStorage' in window && window['sessionStorage'] !== null;
} catch(e) {
  return false;

Source: Dive Into HTML5

Known issues and concerns

Web storage has “a synchronous API that runs on the main UI thread in browsers; as a consequence of that, a race condition can occur if a user has the same site open in multiple windows or tabs running as separate processes. For many applications, that’s never really a problem in practice. But it can cause data corruption—so applications where it’s important to try to ensure that absolutely no data corruption can occur should instead use a more robust storage mechanism such as IndexedDB.”

Source: HTML5 Please


While there are several Web storage polyfills available, HTML5 Please recommends:

Remy’s storage polyfill
Implements local and session storage using cookies.
Implements session storage using the window.name property.

More information

While any of the Source links included above can be used for more information, the following are what I consider the best concise sources to learn more about using the Web storage API:

  • Dive Into HTML5. No. 7. The Past, Present & Future of Local Storage for Web Applications
  • HTML5 Doctor. Storing Data the Simple HTML5 Way (and a few tricks you might not have known)

Last updated on 12 July 2012

Please add any updates or corrections in the comments section below. Thanks!

Return to the Device APIs table of contents page

Leave a Reply