// Tutorial //

How to Use localForage for Easy Async Browser Storage

Published on February 27, 2020
Default avatar
By William Le
Developer and author at DigitalOcean.
How to Use localForage for Easy Async Browser Storage

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 🤓


Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up
About the authors
Default avatar
Developer and author at DigitalOcean.

Still looking for an answer?

Was this helpful?

Hello Willian, great blog… I just want to confirm something… I was over the library’s Github repo moments ago, and saw the last release was on April / 2021… it seems like the project is on stand by, also not see any library’s version marked as “stable”… but anyway… would you recommend it for a production project ?..