Saving User Preferences with Local Storage 💾

TDLR;

Storing user preferences in session storage is really straightforward.
Let's say the user has set their theme, and we want to remember it for next time they visit:

  • Set: window.localStorage.setItem('theme', 'theme-name');
  • Get: window.localStorage.theme

About Local Storage

Local storage, along with session storage is part of the Web Storage API that allows us to store key-value pairs in the users browser. The difference between the two being that local storage persists after the page is closed/ session is ended, and has no set expiration. For this reason, as well as it's very limited access protections, local storage should not be used for storing any sensitive data.

It's also worth remembering that it is synchronous, so each operation called would only execute one after the previous is finished. And in most browsers, local storage is limited to 5Mb.

Functions

There are 5 built in functions on window.localStorage:

  • setItem(keyName, value) - Sets a value to specified key
  • getItem(keyName) - Returns a value for a given key
  • removeItem(keyName) - Deletes an item and it's value
  • clear() - Deletes all data for the current origin from storage
  • key(index) - Returns the key name for a given index (useful for loops)

Browser Support

Local storage is defined in the HTML Living Standard Specification, and supported by all modern browsers (since Chrome 4, Firefox 3.5, Safari 4 and IE 8).

It's easy to check if the users browser supports it with something like:

if (typeof(Storage) !== 'undefined') {
    // Code for localStorage
} else {
    // Alas, no web storage support
}

Example as a Vue Component

Here's another example, this time as a Vue component, where we're saving the users layout