A very large chocolate chip cookie on a white plate

For the longest time - most of the web’s teenage years - information from a website could only be stored on the client side using a cookie. Like the nutrition of most teenagers, cookies were an incomplete answer to the problems of client-side storage, while also being tricky to wrangle in JavaScript.

In the last five years, the web has grown up significantly. Part of that has included client-side storage of data, in the form of the Web Storage API, which eliminates most of the previous limitations of cookies.

Similarities and Differences

Like cookies, the Web Storage API may store information temporarily or “permanently”:

  • for temporary use, the sessionStorage property retains information so long as the browser is kept running. When the user quits the browser, the information is lost.
  • for “permanent” use, we employ localStorage.

This article will concentrate on the (arguably more useful and well-known) localStorage aspect of the Web Storage API.

Simple Storage

The localStorage property takes a key and a value. There are three ways of writing a value using localStorage:

localStorage.decision = "east";
localStorage["decision"] = "east";
localStorage.setItem("decision", "east");

In the example above, decision is the key, and east is the value. All three techniques are equivalent. To retrieve the value, we can use (in the console):

localStorage.decision
> 'east'

localStorage["decision"]
> 'east'

localStorage.getItem("decision")
> 'east'

localStorage always stores strings, meaning that integers and other data types must be converted into strings for storage.

Aside from ease of use, the Web Storage API has a number of significant advantages over cookies:

  • There is a limit of 5MB per origin for data in localStorage, compared to the 3KB of cookies (note that users can alter the maximum storage size for data in their browser, so this space is not completely guaranteed; it can also be altered with the Quota Management API).
  • cookie data has to be transferred in a HTTP request, and read with another request; localStorage can be written and read at any time.
  • cookie data is stored in a single string, which can make parsing the data challenging. As we have seen, localStorage uses a very readable key and value system, of which you can have as many as you wish.
An illustration of a gloomy underground dungeon

Choose Your Own Adventure

As an example, let’s say that we were building a simple adventure game, similar to “Choose Your Own Adventure” books or the first computer text adventures. Each decision made in the adventure will take you to a new page. The first page offers two options:

<p> > West of House
<p>You are standing in an open field west of a white house, 
with a boarded front door.
<p>There is a small mailbox here. You can proceed
<a href='north.html'>north</a> or <a href='south.html'>south</a>

Our adventurer will proceed through a series of linked and branching pages with each decision they make, but we want to remember the first choice they made. To do so, we’ll write their decision to localStorage. At the bottom of the first page, add a script:

<script>
var decisionLinks = document.getElementsByTagName('a');
for (var i = 0; i < decisionLinks.length; i++) {
    decisionLinks[i].addEventListener('click', function(e) {
        localStorage.decision = e.target.textContent;
    });
}
</script>

This script gathers up all the links on the page, attaching an event listener to each that records the text in the link in localStorage before proceeding to the linked page.

Adventurer’s End

Later in our adventure, we want to check the user’s initial choice. On some other page on our site, we present default text:

<p id="conclusion">As you enter the barrow, the door closes 
inexorably behind you. The night is dark and full of terrors. 

For entirely arbitrary reasons, we want the player to die on this page if they first proceeded north on their adventure. At the bottom of the page, add a script:

<script>
var conclusion = document.getElementById('conclusion');
if (localStorage.decision == 'north') {
    conclusion.insertAdjacentHTML('beforeend', ' You have been eaten by a grue.');
}
</script>

If the adventurer first went north, the if decision will evaluate to true, and the user will be eaten; if they start over again, localStorage will be reset with the new decision they make, potentially altering the life-changing consequences when they reach the final page with insertAdjacentHTML.

Choice Matters

The Web Storage API has excellent browser support: every browser supports both localStorage and sessionStorage, including IE8 and up. Given it’s advantages over cookies, there are few reasons to go with the traditional system, unless you want the reliability of PHP… but even then, the cookie could be blocked or erased by the client. For storing data on the client, sessionStorage is an excellent choice.

Photograph by Matt DeTurck, licensed under Creative Commons; illustration by Jordan Grimmer, used with permission.

Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.