Tutorial

How to Use localForage for Easy Async Browser Storage

JavaScript

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

localForage is a convenient wrapper library that smoothes the rough landscape of browser databases. Of which there are several:

  • localStorage
  • IndexedDB
  • and Web SQL

Each of these options was initially designed with the same purpose: providing persistent storage in the browser. The reality is that each of the options has unique strengths and limitations that could make a simple database task in the browser take hours of reading docs.

To install localForage run: $ npm install localforage

Benefits of Using localForage

localForage solves this problem by providing a simple API that imitates localStorage while including other powerful features from other robust databases (like the ability to store blobs that IndexedDB provides).

Below I go over some the benefits you’ll find when using localForage, along with some usage examples!

Imitates localStorage API

You already know the API for localForage if you know localStorage!

import localForage from 'localforage';
const foo = 'hello world';

// Setting...
localStorage.setItem('myuniquekey', foo);
localForage.setItem('myuniquekey', foo);

// Getting...
localStorage.getItem('myuniquekey');   //=> 'hello world'
localForage.getItem('myuniquekey');    //=> 'hello world'

Many of the localStorage methods like removeItem(), clear(), keys() and length() are available in localForage. This makes it almost effortless for webdevs to get going with it!

No Need to Serialize

Perhaps one of the greatest benefits with using localForage is that you don’t need to serialize your values!

const foo = {
  greeting: 'hello world'
};

localStorage.setItem('myuniquekey', JSON.stringify(foo));
JSON.parse(localStorage.getItem('myuniqekey'));
//=> {
//     greeting: 'hello world'
//   };

localForage.setItem('myuniquekey', foo); // 🤯
localForage.getItem('myuniquekey');
//=> {
//     greeting: 'hello world'
//   };

Storing values with localForage feels more seamless than localStorage. This works with a variety of values like arrays, numbers, files, etc and lets you skip the headache of serializing values. 😅

localForage is Asynchronous

localStorage is synchronous. This isn’t noticeably bad for smaller values like a short string or number, however it’s really slow when you need to work with large arrays/objects since they need to be stringified.

localForage is completely asynchronous, and provides a callback or ES6 Promise interface. This makes it more performant than any synchronous library because it won’t block the thread.

const foo = {
  greeting: 'hello world'
};

// ES6 Promise
localForage.setItem('myuniquekey', foo)
  .then((value) => {})    // do something with "foo"
  .catch((error) => {});  // handle errors

// Callback
localForage.setItem('myuniquekey', foo, (error, value) => {});

It’s kinda nice that you can choose between the callback or the Promise interface!

Graceful Degradation

By default localForage prefers using these databases (in this particular order):

  1. IndexedDB
  2. WebSQL
  3. localStorage

It will gracefully degrade if that database isn’t available. For example, WebSQL isn’t available on Firefox Desktop, so it would degrade to localStorage instead. This happens automatically without any action on your part. 🆒

However, if you’d like to set a different order of fallback databases you can use the setDriver() or config() methods:

import localForage from 'localforage';

// Using setDriver()
localForage.setDriver([
  localForage.INDEXEDDB,
  localForage.LOCALSTORAGE,
  localForage.WEBSQL,
]);

// Using config()
localForage.config({
  driver: [
    localForage.INDEXEDDB,
    localForage.LOCALSTORAGE,
    localForage.WEBSQL,
  ],
  name: 'myApp',     // These fields
  version: 1.0,      // are totally optional
});

If you want to provide an exclusive database for localForage to use, pass a single value instead of an array!

localForage.setDriver(localForage.LOCALSTORAGE);

Note that both the setDriver() and the config() methods should be placed before localForage is used to interact with databases.

Wrapping Up

localForage is an easy-to-use and powerful browser storage library! It was developed with the support of Mozilla, and is very well-maintained. Visit the docs website for more guidance on how localForage might work for you 🤓

Creative Commons License