Jump to navigation

Local Storage

"Local Storage enables information to be stored locally on a user's computer"

HTTP is a stateless protocol, meaning that it doesn't retain any information between the browser and server and effectively resets on the next request. For example this website doesn't know anything about your last visit when you when you close and re-open it.

To combat this developers have stored and retrieved the information for when the user comes back. This would typically be done server side, but what about cases where there is no user reference, such as a login, to send to the server?

The information needs to be stored client side and traditionally cookies have been used for this. Local Storage has the following advantages over cookies:

  • It can store far more data
  • Local storage information is never passed to the server
  • It has a better reputation than cookies, which have been used to track people's browsing activity, resulting in people disabling cookies
  • Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.
``` js

// Shane


To store objects we make use of the following JSON methods...

var person = {
  'name': 'Shane',
  'sex': 'male',
  'age': 30,

localStorage.setItem('someone', JSON.stringify(person));
var savedInfo = JSON.parse( localStorage.getItem('someone'));

Local Storage data will exist forever until it's deleted, either by some code or via the browser settings. If you want the data to be maintained only until the browser window closes you should use sessionStorage.

A nice usage example would be saving information from an API, so that it doesn't have to be downloaded each time.

if(localStorage && localStorage.getItem('someone')){
  var savedInfo = localStorage.getItem('someone');
else {

Example taken from from Smashing Magazine.