Quick Tip: Make IndexedDB a Breeze With LocalForage

IndexedDB is a local NoSQL database that allows developers to safely store data in the browser. It has great cross-platform support, works with any type of data, and is powerful enough for building apps that work offline.

Although it is probably the best solution for client side storage, IndexedDB has one critical flaw - it's low-level API. Things like transactions, cursors, and a lack of support for promises over-complicate IndexedDB and make it exhausting to work with.

Thankfully, there is a more dev-friendly way!

LocalForage to the Rescue

LocalForage is an open-source JavaScript library that makes working with in-browser databases much more enjoyable. On the outside its API looks very similar to localStorage, while under the hood it hides the entire arsenal of IndexedDB features.

Compared to the 15 lines of code required to do anything with IndexedDB, with localForage creating a database and accessing its entries comes down to using a simple method. It also adds much needed support for promises plus other helpful utilities.

Installation

Adding localForage to a project is quite simple. Either drop it directly into the HTML:

<script src="assets/js/localforage.min.js"></script>

Or install using a package manager of your choice:

npm install localForage --save

The library is browserify-friendly and can be used with bundlers like Webpack. The localForage interface doesn't require any additional initialization or loading so we can use it as soon as it becomes available.

import localforage from "localforage";
localforage.setItem('key', 'value');

Writing to the Store

Since we don't have to setup or create new databases, we can go right in and add some data to our store. This is done via the setItem method, taking two parameters - key and value.

  • key - Unique, case-sensitive identifier that will be used whenever we want to access that item later on. Using setItem again on the same key will overwrite it.
  • value - The data we want to store. It can be any valid string, number, object, array or file blob.

The process is asynchronous so if we want to do something else with the data and handle errors we have to use a promise or callback.

var hexColors = {
    red: 'ff0000',
    green: '00ff00',
    yellow: 'ffff00'
};

localforage.setItem('colors', hexColors).then(function (value) {
    console.log(value.red);
}).catch(function(err) {
    console.error(err);
});

Reading from the Store

Fetching items from the database works in pretty much the same way. We simply use getItem, pass the name of the key, and use a promise to work with the data.

localforage.getItem('colors').then(function (value) {
    console.log(value.red); 
}).catch(function(err) {
    console.error(err);
});

If we try to get a key that doesn't exist the promise will resolve successfully but the value inside will be null.

Other Methods

LocalForage has some other useful methods for working with the database. They are all just as easy to use as setItem and getItem, also supporting promises or callbacks.

  • removeItem(key) - Removes the key/value pair from the store.
  • keys() - Returns an array of all the keys' names (only the names).
  • iterate(callback) - Works like forEach, expecting a callback function and going over all the key/value pairs.
  • length() - Returns the number of items in the store.
  • clear() - Wipes out the store.

Multiple Databases

So far the examples in this article used the localforage interface directly resulting in a single global store. If we need more then one store we can create as many instances as we want using createInstance:

var dogStore = localforage.createInstance({
  name: "Dogs"
});

var catStore = localforage.createInstance({
  name: "Cats"
});

Each store is completely independant and has access only to it's own data (NoSQL databases are mostly non-relational).

dogStore.setItem('Jake', 'Good boy');
catStore.getItem('Jake').then(function (value) {
    console.log(value);  // Will result in null
});

Conclusion

If you are looking for a simple way to manage client-side databases, localForage is one of the best tools available right now. It's API provides all the needed utilities, giving you enough freedom to organize your storage however you see fit.

  • The official docs - The project's documentation isn't very detailed but covers most of what you need to know.
  • localForage on GitHub - The repo is very active, if you have any problems with the library make sure to check the issues here first.
  • angular-localForage - Plugin for working with localForage in Angular.
Presenting Bootstrap Studio

a revolutionary tool that developers and designers use to create
beautiful interfaces using the Bootstrap Framework.

Learn more
Web Browser Frame DevKit Box Mouse Cursor

Related Articles

Comments 3

  • Thanks for the fantastic article, Danny! I have tried using IndexedDB in my web app, but as you've written it is so low level that it is a paint to work with. I only wish I had known about LocalForage earlier.

  • Thks Danny for this tutorial but whats the limit of data that can be stored localForage

  • There is no fixed limit on the amount of data you can store in localForage and indexedDB. The size of available storage depends on how much space is on the user's hard drive and which browser he is using.

    Here is a great article on that topic:
    https://www.raymondcamden.com/2015/04/17/indexeddb-and-limits