A Look Into localStorage

A post from Oleg Yanchinskiy

This weekend I decided to look into into localStorage and sessionStorage to figure out how this relatively new HTML5 feature works. In past applications I've resorted to storing persistent data server side. I wanted to explore the API features, and what some common uses for it might be.

What have we used in the past?

Traditionally web cookies have been the de-facto client storage strategy for storing persistent information about the user client side. They were created in the early 90's and integrated into Internet Explorer in 1995. There are a couple different types of cookies (such as persistent or tracking cookies which provide your browsing info to advertisers), but their purposes are ultimately similar - to remember the stateful information of the user.

There were other attempts by individual browsers to develop their own versions of client side storage. In 2007 Google developed Gears, which was a software that -

"enables more powerful web applications, by adding new features to the web browser. It allows some online files to be used offline"

Gears contained 5 different components, one of which is a SQLite database module that allowed data to be stored locally. Eventually most of Google Gears' components would be integrated into HTML5 in one form or another.

So why not just use cookies? Cookies have a number of limitation which ultimately make it a poor choice for storing information client side.

  • Cookies are only limited to 4KB of data
  • Cookies are unencrypted unless your entire app is over a SSL connection.
  • Cookies are included in every HTTP request which may send unnecessary data and slow down your application.

What are we looking for and why do we need it?

  • A lot of storage space on the client
  • Persistent data beyond a reload
  • Data that that isn't transmitted to the server (unless you do it manually)
  • Something that doesn't expire or get cleared (unless you explicitly do this)

Persistent storage is one area where native (iOS, Android) applications have held an advantage over web apps. In native apps the operating system gives you access to a number of storage solutions allowing you to remember and retrieve user preferences. LocalStorage bridges the gap and provides an easy solution for web apps.

localStorage VS sessionStorage

localStorage maintains a separate key-value storage container for each given origin.

sessionStorage does the same thing but is only persistent while the browser is open - including reloads and restores.

The Interface

localStorage and sessionStorage are properties of the global window object.

The API has a number of methods & properties. I'll keep it brief and describe the major ones:

  • getItem( keyAsString ) - Retrieves the value based on the key or null if the key doesn't exist.
  • setItem( keyAsString, value ) - Sets the value with the associated key. You can pass anything in as the value but one important thing to note is that all values are stored as strings. It's up to you to parse your values accordingly.
  • removeItem( keyAsString ) - Removes the key-value pair from storage.
  • length - Property which returns the number of keys in storage.
  • key( indexOfKey ) - localStorage keys are saved in indexed order. You can find out what a particular key is by calling the key method and passing in an index. If a key doesn't exist at that index, you'll get null.
  • clear() - Clears everything in storage.

Events - How to track changes

Ok so you've made some changes to the localStorage, how do let the rest of your applications know that happened? Well the API makes this really easy by integrating a storage event which is fired whenever setItem(), removeItem(), or clear() are called AND something actually changes.

Lets see a quick example of how to set this up:

window.addEventListener('storage', function(event){	
	console.log(event);
});

We get the following properties from the event object in addition to others -

  • key - The key being changed.
  • oldValue - The old value of the key being changed.
  • newValue - The new value of the key being changed.
  • url - The address of the document whose key changed.
  • storageArea - The storage object that was effected.

How much data can we store?

Each origin can store up to 5MB of data in localStorage. Users can give certain sites more space but that is a user initiated event. How much is 5MB's? Given that 1 character is 1 byte, you can store roughly 5 million characters.

When should I use localStorage?

Essentially, you should use localStorage any time you want to remember some sort of user preference. If your site has login and you'd like to save the user a step, you can store their username in localStorage. Additionally if you have a set of instructions which the user should read only on their first visit, you can store this state as well. I'm sure there are plenty of other uses for this handy API.

Here are the corresponding Github repo and website to demonstrate how to store values and work with the storage event (based on the MDN example).


Resources

  1. Dive into HTML5
  2. MDN Web Storage API
bleak theme by Jack Preston