An Introduction to HTML5's localStorage

Did you know that localStorage works as far back as Internet Explorer 8? There's no good reason to not be using it!

The Basics

Let's start out by saving a very simple piece of information to local storage, like so:

localStorage.setItem('name', 'Luke');

Then to retrieve it just do this:

localStorage.getItem('name');

Beautiful. Simple. Easy.

The Next Level

Okay, so you've just saved and retrieved a single piece of information. Let's see what else we can do.

You should know that localStorage is only capable of saving strings. Numbers get converted into strings and objects will save as the string, "[object Object]".

But, we can use the JSON.stringify() function to turn an object into a string, which can then be saved to localStorage.

localStorage.setItem('user', JSON.stringify({
  name: 'Luke',
  age: 25,
  occupation: 'Web Developer'
}));

If you do localStorage.getItem('user') right now, it will return the stringified object:

"{"name":"Luke","age":25,"occupation":"Web Developer"}"

This isn't quite what we want, so we'll use the JSON.parse() function to convert it back into an object:

JSON.parse(localStorage.getItem('user'));

Now you've received your object back in a usable form!

Clearing the Storage

When the browser's cache is cleared, all localStorage is erased.

To manually erase all localStorage do this:

localStorage.clear();

To erase a specific localStorage item, do this:

localStorage.removeItem('item_key_here');

Max Storage Size

There is a maximum size for the information saved to localStorage. In Google Chrome it's 2.5 MB per origin, in Mozilla Firefox and Opera it's 5 MB per origin and in Internet Explorer it's 10 MB per origin. 'Per origin' meaning per domain (www.yoursite.com) on a single visitor's browser.

I hope you found this useful. Local storage is a great alternative to cookies and the browser support for it is great, which means you can start using it in real projects right now!

Ready to discuss your project?

Send me a message and I'll get back to you within one business day.

Let's Talk