Introduction to HTML5 Web Storage

Introduction to HTML5 Web Storage

Web Storage is a new HTML5 API offering important benefits over traditional cookies. Although the specification is still in W3C draft status, all major browsers support it already.

This means you can start using the API’s sessionStorage and localStorage objects (we will discuss these later on) and enjoy their benefits.

The Limitations of Cookies

First, there were cookies. They have been a huge driving factor for the Web since the early days. In both a good and a bad way.

For example, cookies allow us to login automatically to sites we use frequently, such as Gmail and Facebook.

On the other hand, with cookies, our search and browsing history can be tracked and our privacy is a concern.

Another problem with cookies is that they have data-capacity limitations. The data storage limit of cookies in many web browsers is about 4 KB per cookie, based on a deprecated 1997 specification recommending a minimum of 4096 bytes per cookie.

Although most browsers allow 30 to 50 cookies, so if you exceed the 4 KB limit of one cookie you could create another one, this is still a real limitation.

This is why developers usually only store user and/or session identifiers in cookies, and then use server-side databases to store and get the rest of the user data.

Additionally, an often-overlooked side effect of cookies is that they are always sent with every HTTP request (usually even for images) resulting in more data being sent over the wire.

Moving Forward with Web Storage

Web Storage picks up where cookies left off. The strength of Web Storage is in at least two things.

First, ease of use for web developers: It has a simple API to get and set key/value pairs (we will get more into this below).

Secondly, the amount of space it provides: the specs default the disk space quota decision to the user agent (i.e. the web browser developers) and most of them offer no less than 5 or 10 MB to be stored per domain. This means we can store more than just basic user/session info on the client-side: user preference settings, localization data, temporary offline storage for batching server writes and much more.

The data being stored can be accessed using JavaScript, which gives you the ability to leverage client-side scripting to do many things that have traditionally involved server-side programming and relational databases.

Session Storage and Local Storage

It is important to know that there are two types of Web Storage objects: sessionStorage and localStorage.

sessionStorage is only available within the browser tab or window session. It’s designed to store data in a single web page session.

localStorage is kept even between browser sessions. This means data is still available when the browser is closed and reopened, and also instantly between tabs and windows.

Web Storage data is, in both cases, not available between different browsers. For example, storage objects created in Firefox cannot be accessed in Internet Explorer, exactly like cookies.

Where to Use Web Storage

Some examples of implementation scenarios include storing the data for an online to-do list (then pushing to the server in intervals instead of in real-time) or saving products that the user places in his shopping cart. The data can be made available between page requests, multiple browser tabs, and also between browser sessions using localStorage.

Your apps can actually be used offline completely using localStorage. Data can then be sent and stored server-side when the user is online again.

From another perspective, Web Storage can be a great performance win when some static data is stored on the client to minimize the number of subsequent requests. Even images can be stored in strings using Base64 encoding.

For the examples mentioned above, it makes sense to use localStorage. You may be wondering, then, when you should opt for sessionStorage.

In some cases, you simply want to get rid of the data as soon as the window is closed. Or, perhaps, you don’t want the application to interfere with the same application that’s open in another window (e.g. when running two instances of a Scrabble game or running multiple unit tests simultaneously, you don’t want data to collide). These scenarios are served best with sessionStorage.

Using the Web Storage API

It’s really simple. It’s probably best just to show it:

sessionStorage.setItem('myKey', 'myValue');
var myVar = sessionStorage.getItem('myKey');

localStorage.setItem('myKey', 'myValue');
var myVar = localStorage.getItem('myKey');

Note that the interface for creating sessionStorage and localStorage is identical and that they are global objects.

You can use the .setItem method to set the key and its value, and then .getItem to retrieve the value of a specific key.

Note that we can only store strings, which is a significant drawback. However, to get around this, we can store and retrieve string representations of JSON objects by using the JSON.stringify() method to store a string, and JSON.parse() to create the original object from that string.

Web Storage Events

Whenever we store data in localStorage, the storage event is fired in other browser windows/tabs.

What is so great about that?

This event can be used to overcome that so-called race conditions between browser windows/tabs: If the user has the same site open in different tabs, this event can be used to synchronize the data. (This was actually quite an issue with cookies.)

The storage event is only fired when the new value is not the same as the old value. The storage event contains the key, oldValue and newValue properties of data that has changed, which you can access in code.

Example code:

window.addEventListener('storage', function(event) {
  console.log('The value for ' + event.key + ' was changed from' + event.oldValue + ' to ' + event.newValue);
  }, false);

Above, we create an event listener on the window object for the storage event. When the event happens, a function that logs the key, oldValue and newValue to your console (e.g. Firebug or Google Chrome Developer Tools) is executed.

Browser Support for Web Storage

You are encouraged to start using this API today. Web Storage is implemented in IE8 and in all modern browsers (i.e. starting from Firefox 3.5, Safari 4, Google Chrome 4, and Opera 10.50).

The storage event was added later, but is available in at least Firefox 5, Safari 5, Chrome 12, Opera 10.5 and reportedly in IE9.

Security Concerns

Please be aware that using Web Storage is really not more secure than cookies. With greater power, comes greater responsibility.

SSL does a great deal of resolving security issues. (SSL means the client and server communicate only encrypted data). This is why you see more and more websites using the more secure https protocol.

In any case, do not store sensitive data (like passwords and credit card numbers) on the client-side, nor send this kind of data to the client.

Final Notes

Web Storage is sometimes referred to as DOM Storage, this is the same thing. The latter is derived from the fact that the data is actually stored in JavaScript’s window object (i.e. window.localStorage and window.sessionStorage).

And last but not least, keep in mind that Web Storage, just like cookies, can be turned off by the user. So you always need to implement a fallback mechanism in case window.sessionStorage or window.localStorage is not available.

Further Reading

Related Content

About the Author

Lars Kappert is a front-end web developer and IT specialist from the Netherlands. His development style focuses on pragmatism and creating web products for real-world scenarios. Visit his portfolio site: WebPro. Follow him on Twitter as @webprolific and connect with him on LinkedIn.

This was published on Aug 15, 2011


Helen Aug 15 2011

For what kind of person is this article written?

vsync Aug 15 2011

I liked the idea of listening to the storage even, to communicate with other tabs/windows. I have been using localStorage for my online Sudoku game to save games:

Evert Aug 15 2011

Quote: And last but not least, keep in mind that Web Storage, just like cookies, can be turned off by the user. So you always need to implement a fallback mechanism…

Oh great, so even more code to write. Not only do we need to test for cookies and provide a fallback, now we also need to test for web storage and write a fallback. Couldn’t we just use the fallback and be done with it?
Seriously though, how many users have this feature turned on, will determine if this will become popular and a viable substitute for cookies.

Glenn Aug 15 2011

Nice article Lars. First I’ve heard of this. Still don’t fully understand the difference between HTML5’s sessionStorage, and the use of $_SESSION[] variables. Guess I’ll have to do some experimentation … :)

Jacob Gube Aug 15 2011

@Evert: Fallback is a stopgap while we’re in this transitional period, where a significant amount of Internet users are still not using Web-Storage-capable browsers.

Eventually we won’t need to defensively code against this scenario. Just like how we now safely assume and require that JavaScript (or even Flash) is turned on and available when users use our web apps (most mainstream RIAs require JavaScript-capable user agents for them to work properly).

Using Web Storage now means many of your users, those that do use future-standards-complaint browsers, can have the benefits of Web Storage — working offline, lowered page response times through the offloading off what has traditionally been server-side/relational database work (which is affected by internet connectivity and how fast your web server is) to the client-side, etc.

How many users have this feature available? It depends on the site; here on Six Revisions, most users use Web-Storage-capable user agents (based on anonymous aggregated data that Google Analytics provides us), and by default, browsers have it turned on. So, it’s safe to assume, then, that most people coming to this site have Web Storage capabilities.

At the end of the day, this is where we’re headed; this isn’t an option, it’s happening as we speak, and most notably in mobile web apps.

It’s completely your choice, as a developer, to be left behind.

@Glenn: Let me take a crack at it (even though your question’s directed to Lars). One difference is $_SESSION[] requires server-side scripting (that syntax is PHP, but other server-side scripting languages have a similar feature).

With web storage, you use client-side scripting; specifically JavaScript.

So one big difference is that your code’s logic is exposed to the public with Web Storage (e.g. what you do with the session data).

The other is you don’t need a server to set and get the data; as long as your user has your script, if they suddenly drop connection (and you wrote your app to do so) they can continue working. This is great for mobile internet-capable devices.

All the differences — benefits, disadvantages, when to use which — between server-side session variables vs. client-side storage all circles back to server-side vs. client-side.

Wavebourn Aug 15 2011

Fallback mechanism is needed, because current implementations are based on additions to markup language developed for hypertext representation of scientific publications. If we want finally to start using something initially designed for Web applications, we have to live some time with legacy software that will be used anyway during transition time. And support of fall-back mechanisms is the price we pay for possibility to use Web – applications before appropriate technologies were available.

Thomas van der Ploeg Aug 16 2011

I do not believe in that “We’re ready!” propaganda. The transition period you are describing has been going on since IE6. The numbers you throw are also generic: SixRevisions is a web community, hence the fact that mostly developers with modern browsers will visit.

The masses still use outdated versions. It frustrates me that the browser industry has not learned anything from the big IE6 dilemma: the all – with one exception – do not provide adequate update mechanisms. The exception is Google Chrome, which has such an elegant and aggressive mechanism that it will update no matter what.

The guys over at Mozilla screwed up real good with their release of Firefox 4, also a milestone in how seriously over-hyped the HTML5 trend is. This is not a good start for the introduction of Firefox 4, since people are already getting annoyed. The trend of incremental version numbers with minor improvements also does not help anything.

I am sorry. I want to be excited, but it’s hard for me since I see the same things happening again and again. More on topic, I think the Web storage has its positives, but it will remain to be seen how well it will be implemented. Personally, I think its one of the least interesting improvements, since were more and more heading towards cloud computing.

Evert Aug 16 2011

I am with Thomas on this one. I have been making websites for about 15 years now and if only I had gotten a euro for every time people told me “this is the new standard”, and “just wait and see, eventually all UA will comply to this”.

Fact is, that standards and features on the Web are not exempt from greed and ego, and in the end every new standard or technology is just that: one of many.

Obviously any good web designer/developer will not choose to be left out, but ultimately that will mean that with every new idea, extra work is generated and even in the long run, people will be left out.
Only recently have I stopped supporting IE6, but even so I must still include a fallback for it. And I suspect I still will 5 years from now.

But even when you state that all users that have modern browsers will benefit, this is also not true. I use modern browsers, and every time a website asks me if it can use local storage I say NO. And I suspect many established users will do the same, because they were told never to allow access to their computer if they didn’t ask for it, because then you leave your system wide open for hackers.
No matter if this technology is safe to use. First you must educate the whole of the community about that. And they have had years of experience with malicious software and adware.

So forgive me if I cautiously think that this feature will be many, many years in the future before it can even remotely be relied upon to be available.

Philip Aug 16 2011

Isn’t “localStorage” the way a web app can be designed to (seamlessly) switch the user from ‘online’ to ‘offline’ usage.

Maybe to allow working/reading/viewing to continue when connections are unavailable.

Or because a pre-downloaded-to-memory resource will surely be faster than a fetched-on-demand-over-the-internet one?

Agree 1000% with Thomas’ statement above

Lars Kappert Aug 17 2011

For anyone being hesitant towards new features like this, I’d like to mention the following. I think it’s impossible to release new and matured features based on unfinished specs and without real-world usage; and its impossible to finish specs without real-world usage. This is a very innovative eco-system and I, for one, really like the fast pace of it, next to the fact that we seem to have a healthy competition going on between browser vendors. The process of users switching/updating their browser may be slow, but it does happen.

The end-user wins I think, and that wouldn’t be the case without HTML5, CSS3, new Javascript API’s, libraries and modern browsers. No matter how many mistakes browser vendors may have made, not many people will stick to IE6 if they have a choice.

Regarding the “cloud computing” comment and Philips question: data that is available locally will always be faster than data has to be downloaded first. And it is available when offline as well. So it’s still a great (and important) feature in cloud-based apps (potentially the whole app with data can run in the client, and updated remotely when online).

Henry Louis Aug 17 2011

How much of memory is available for web storage? Any idea?

Frankly, as negative as their posts sound, I have to wholeheartedly agree with Thomas and Evert. Both are spot-on with their scathing remarks about browser use and updating. And their complete lack of faith in this new “feature”.

I see no benefit in implementing Web Storage over PHP session variables or cookies, other than the previously mentioned benefit to mobile browsers.

JS can be turned off (effectively breaking Web Storage) and cookies can be disabled, but (as far as I know) users have no control over PHP sessions…

Vibrance Aug 17 2011

Have been reading on this recently:

Its a concept where some would take a lot of getting used to.

Jacob Gube Aug 17 2011

@Thomas van der Ploeg, @Philip and @Mark: First, I can completely see where you are all coming from, so I appreciate and thank all of you for taking the time to share here in the comments. It is frustrating how technology isn’t in sync with the mainstream users’ browser choice. And Web Storage, for all its advantages, is a hard sell when the CTO of your company, client, your manager, [insert decision-maker here] is still using IE7 and can’t see/use all the wonderful things that took you extra project time to develop.

Swamykant Aug 22 2011

Very useful post. Thanks for sharing your knowledge.

Daquan Wright Aug 23 2011

I think web storage is just going to bridge the gap between native desktop apps and online web apps. The more we can streamline processes and keep data that the user has previously been in contact with from needing to be re-fetched, the web will become a brighter place. :)

I’m pretty excited for this feature, though I hadn’t had to use it yet.

Daquan Wright Aug 23 2011

@Vibrance: Do NOT go to w3schools, it’s filled with bad information:

If you keep it up, I’ll cry and bring out the pitch forks. :)

Great Tut…

great article ,it helped me a lot for my HTML5 presentation thanx :)

This comment section is closed. Please contact us if you have important new information about this post.