Using local storage in web apps

Published on 2017-01-23

Web applications are no longer bound by the old ways of client/server releationsships. Browser vendors eg. are working hard to press new standards for web applications that makes it easier to implement native-like applications right in the browser.

With local storage a web application doesn't even need a server to store data!

What is local storage?

Local storage is a way for web applications (web pages) to store information locally in the browser.

If you store information in cookies - the traditional way - there are some disadvantages:

  • The cookies are transferred on every request - the server knows everything! And the server can manipulate the content of the cookies.
  • Cookies are transferred in the header of the HTTP request - there is a limited size of those headers.
  • Cookies have an expiration time - after that they are gone.

Local storage is a key-/value-store available in all newer browsers. When you save stuff in local storage it will be there next time the page loads.

How is local storage supported?

As mentioned local storage is supported in all newer versions of all major browsers. Check out the compatiblity overview.

How is local storage used?

The specification (from Mozilla) have all the details on how to use local storage, check it out here.

Here are some examples on how to use it (these are also found in the documentation).

The localStorage is an element on the global window reference (it can be used directly though).

To set a value:

localStorage.setItem('foo', JSON.stringify({ 'name': 'Going Full Stack', 'url': 'https://goingfullstack.com/' }))

and to get the value back:

var foo = JSON.parse(localStorage.getItem('foo'))

and, finally, to delete the value, or remove all items:

localStorage.removeItem('foo')
localStorage.clear()

The API comes with events etc. - if interrested you should look into these details!

When to use local storage?

There are many use cases for local storage.

In my opinion it is one of the most under used technologies in the new web stuff - and there are many things it can be used for, among others:

  • Avoiding using a server
  • Caching values from the server
  • Saving elements for later synchronization (with the server)

My recommendation is to start thinking where it would make sense to include local storage in your projects - I'm sure there will be many places where it would be a benefit.