Web Storage: Local Storage & Session Storage

In the transition from HTML4 to HTML5, one of the additions of note is web storage. Web storage comes in 2 forms: local storage and session storage (the difference between the 2 will be explained subsequently). But first let’s cover the basics. What is web storage? Basically, it is a method of storing data locally in the user’s browser using key value pairs of data like so…

localStorage.setItem('food', 'Burgers');
localStorage.getItem('food'); // Burgers

By setting a key (food), we can store a value (Burgers) locally.

But what’s so different about this? Browser cookies also accomplish this and cookies have been around forever. Good question. There are 2 key differences between web storage and cookies mainly having to do with size capacity and data transfer.

Firstly, web storage provides far greater storage capacity than cookies. Where cookies are limited to 4 KB, the benchmark capacity for Web Storage is 5 MB. This has been known to vary between browsers. Some offer more space and some offer less, but in any case it’s substantially more space than cookies give you.

Secondly and very significantly, where cookies are sent with each HTTP request after they are set, web storage data is not! This is an extremely important distinction because you can safely store values locally on the users machine and you do not have to worry about the data being sent over the wire. So, for example, when using HMAC to secure a REST API you need to store a secret private key somewhere on the client side to be used in creating a hash that will be sent along with requests — but you don’t want to send the key itself. Web Storage is one possible option (among others) where you can choose to store this key.

And really, web storage is a bit nicer and simpler than dealing with cookies…

// Set Cookie
var date = new Date();
date.setTime(date.getTime()+(1*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
var name = "food";
var value = "Burgers";
document.cookie = name+"="+value+expires+"; path=/";

// Read Cookie
var cookieValue;
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') 
        c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) 
        cookieValue = c.substring(nameEQ.length,c.length);
}

console.log(cookieValue);  // Burgers

Although a lot of the above can be abstracted into different functions that you can call in the same manner as you would with web storage, web storage offers a much simpler implementation out of the box.

Web Storage Objects: localStorage and sessionStorage

As mentioned prior, web storage comes in 2 forms: localStorage and sessionStorage. What is the difference between these? W3Schools explains this rather nicely…

The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year… The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window.

So if you want the key-value pairs to still be around in the user’s browser after he or she has closed it out you should use the localStorage object. If you don’t, use sessionStorage.

Testing for Support

The first thing you want to do in your JavaScript application code before you use web storage is to test whether or not your browser supports it and if it does not then fall back on solutions you have for other browsers if you need them.

if(typeof(Storage)!=="undefined")  
    // localStorage and sessionStorage are supported
}
else {
    // Not supported
}

You could also use a tool like Modernizr if you wanted to as well.

Getting & Setting Values

With a lot of things in JavaScript there are many different syntaxes a developer can use to accomplish a particular aspect of functionality. For web storage there are 2 forms you will generally see for getting, setting, and deleting items.

    // setting key/values
    localStorage['name'] = 'Joe';
    localStorage.setItem('name', 'Mike');
    localStorage.setItem('food', 'Burgers');
        
    // getting key/values    
    console.log(localStorage['name']);
    console.log(localStorage.getItem('food'));

    // deleting key/values    
    localStorage.removeItem('food');

    console.log(localStorage.getItem('food'));    

All of the above usages of the localStorage object could be replaced with the sessionStorage object like so…

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

Overall, web storage offers web developers yet another flexible tool to implement functionality in a website or web application. It does have its limitations though. Because web storage is just a set of numerous key-value pairs, it doesn’t scale tremendously well if you need tons of different values nor does it really have a a sophisticated API for sorting or searching for anything. For that, developers often look to other client-side data storage options such as IndexedDB if those features are needed. But for simple values, it does the trick rather nicely.

, 9bit Studios E-Books

Like this post? How about a share?

Stay Updated with the 9bit Studios Newsletter

0 Responses to Web Storage: Local Storage & Session Storage

    Leave a Reply

    Your email address will not be published. Required fields are marked *