Tutorial

How to Use localForage for Easy Async Browser Storage

Published on February 27, 2020
Default avatar

By William Le

How to Use localForage for Easy Async Browser Storage

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking 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 🤓

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
William Le

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
1 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

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 ?..

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel