Client-side Storage (Focusing on Local & Session)

Supported Browsers: Opera 10.5+, Firefox 3.5+, Safari 4.0+, IE 8.0+, Chrome 4.0+

By Alexander Jones,

Introduction

This is an overview of client-side storage, which is a general term that is being used for many separate but related API’s including Web Storage, Web SQL Database, Indexed Database and File Access. The main focus is that each of these different functions provides specific ways to store data on the user’s hard drive instead of on the server. The main reasons for this are:

  • To make the content available offline
  • To improve performance
  • Content persisting after a page refresh
  • Data isn’t transmitted to the server

Before HTML5, all attempts to achieve this were unsatisfactory in many different ways and there’s a lot of useful information over at Dive into HTML5 which talks about the history of local storage hacks before HTML5.

1. Crumbling Cookies: The Current Problem

An example issue of this current method of storing data on the client side includes cookies, which were invented early in the web’s history, and able to be used for persistent local storage of small amounts of data. But they have three quite big "game-breaking" downsides:

  • Low size: Cookies generally have a maximum size of around 4KB, which is not much good for storing any kind of complex data.
  • It’s difficult for cookies to keep track of two or more transactions on the same site, which might be happening in two or more different tabs.
  • Cookies can be exploited using techniques such as cross site scripting, resulting in security breaches.

As mentioned above a solution is required, providing data offline, not being transmitted to the server and persisting after page refreshes.

2. Going Forward with HTML5

Mark Pilgrim discusses in his A Place To Put My Stuff Article: So this is the problem that HTML5 set out to solve: to provide a standardized API, implemented natively and consistently in multiple browsers, without having to rely on third-party plugins.

So what is a definition of HTML5 storage? In its basic form, it’s a way for web page to store named data locally, within the client’s web browser.

Like cookies the data persists after a user navigates away from the web page, closes the browser tab or even exits the browser itself. But unlike cookies, this data is never transmitted to the remote web server.

HTML5 storage is implemented natively in web browsers, meaning that it is available without any third party plugins. The most basic and most popular technique, "Web Storage", consists of two APIs: Local Storage and Session Storage. Session storage only lasts as long as the current window is open, so is suitable for a single interaction, while Local Storage lasts across browser sessions, like all the other mechanisms, and is therefore the more popular form of Web Storage.

In both cases, the store is simply a key-value map, where the keys are strings and the values can be any data structure.

Which Browsers supports HTML5 local storage and session storage? Well luckily, pretty much every browser supports it, even IE8. However, it’s useful to check if your browser supports local storage if you want to experiment with developing, here’s a simple way of detecting support:

Instead of writing this function yourself, you can use Modernizr to detect support for HTML5 Storage.

if (Modernizr.localstorage) {
    // window.localStorage is available!
} else {
    // no native support for HTML5 storage :(
    // maybe try dojox.storage or a third-party solution
}

3. Using HTML5 Storage

DOM storage lets you store data between browser sessions, share data between tabs and prevent data loss (for example from page reloads or browser restarts). The data are stored as strings (for example a JSONified JavaScript object) in a Storage object. There are two kinds of storage global objects: sessionStorage and localStorage which both use the following API:

window.localStorage and window.sessionStorage {
    long length; // Number of items stored
    string key(long index); // Name of the key at index
    string getItem(string key); // Get value of the key
    void setItem(string key, string data); // Add a new key with value data
    void removeItem(string key); // Remove the item key
    void clear(); // Clear the storage
};

Shwetank Dixit discusses in his Web Storage: easier, more powerful client-side data storage: Both Session and Local Storage will typically be able to store around 5Mb of data per domain, which is significantly more than cookies.

Session Storage

Session Storage has one purpose: To remember all the data in your session, and forget it as soon you close the tab (or window) you are working in, which is mostly for security reasons.
The first stage is to have a look at setting and retrieving data, this begins with setting a key value pair in session:

sessionStorage.setItem(yourkey, yourvalue);

To retrieve the data again you would 'get' the data:

var item = sessionStorage.getItem(yourkey);

The next step is to store value inside the session storage:

sessionStorage.setItem('name', 'alex');

and then retrieve it using:

var name = sessionStorage.getItem('name');

An example of when session storage would be used is when a page could have a checkbox that the user ticks to indicate that he wants an ice cream. A later page could then check, from script, whether the user had checked the checkbox or not, and if the user had multiple windows opened on the site, each one would have its own individual copy of the session storage object.

Local Storage

Local Storage is used if you want the data to be stored for more than a single session. When a page uses Local Storage, the page (or window) can be closed and re-opened, and still show the saved data — it provides persistent storage. Saving and retrieving data in Local Storage works similarly to Session Storage: it uses the same function names setItem() and getItem().

An example of when local storage would be to count the number of times a person has visited a Web page. To save a sentence in Local Storage you write something like this:

localStorage.setItem(1, 'This is a sample sentence');

Then to retrieve it:

var data = localStorage.getItem(1);;

Removing & Clearing Data

There is also a number of methods for removing the data from session and local storage. The removeItem() method is used to remove a particular item from the list.

var item = sessionStorage.removeItem(yourkey);

It’s important to know that you can also just reference a data item’s key and remove it from the list that way:

var items = sessionStorage.removeItem(1);

The clear() method is used to clear all items in the list; you use it in the following way:

var items = sessionStorage.removeItem(1);

In both Session Storage and Local Storage, the clear() function has the same objective - to clear all the values in list. This means that if you call, say localStorage.clear() then it will remove all local storage from that origin (the website and other pages, not sub domains).

4. A Simple Example

Let's have a look at a simple example of session storage, where a user can refresh the page as many times as they wish and it will count how many times they do this, once the tab is closed the data will disappear.

Firstly, lets create an empty div called "sessy".

<div id="sessy">
    </div>

Followed by a script tag with the following code. The following if statement first looks to if there is not a current session storage, if this is the case the counter = 0. Else, it will increment from the current value and keep counting per page refresh:

<script>
    if (!sessionStorage['counter']) {
        sessionStorage['counter'] = 0;
    } else {
        sessionStorage['counter']++;
    }
    document.querySelector('#sessy').innerHTML =
    '<p>This sample has been run ' + sessionStorage.getItem('counter') + ' times</p>' +
    '<p>(The value will be available until we close the tab)</p>';
</script>

To see a couple more simple demos about session and local storage have a look at my demos: Local Storage → and Session Storage →.

5. Conclusion

In this article I have only touched on the principles of client storage, and just focused on local and session storage. There's an awful lot more to look at and get excited about including Web SQL Database, Indexed Database and File Access.

The overall purpose and achievement is that it brings a standardised approach to storing data on the client side. The standardisation of client side storage can already be used and enjoyed in the major web browsers as shown with the browsers talked about in this article.

One of the biggest advantages is that the API is easy to apply and the consistency across browsers makes it even easier to use and brings the web browser ever closer to the desktop 'app' experience.

The Next Step

As there is still a huge amount to learn and cover, another article will be on it's way soon about this technology. But for now, below are some brilliant articles and examples to get stuck into: