How to Use IndexedDB — A NoSQL DB on the Browser
By: Viduni Wickramarachchi
Tags: NoSQL, Frontend Development, Indexeddb, Database, Client Side Storage

How do we use Indexed DB in our applications?

In the following section, we’ll look at how to bootstrap an application with IndexedDB.

1. Open the database connection using “ window.indexedDB"

const openingRequest = indexedDB.open('UserDB', 1);

In here, UserDB is the database name and 1 is the version of the DB. This would return an object which is an instance of the IDBOpenDBRequest interface.

2. Create object store

Once the database connection is open, the onupgradeneeded event will be fired, which can be used to create object stores.

// Create the UserDetails object store and indexes request.onupgradeneeded = (event) => {

let db = event.target.result;



// Create the UserDetails object store

// with auto-increment id

let store = db.createObjectStore('UserDetails', {

autoIncrement: true

});



// Create an index on the NIC property

let index = store.createIndex('nic', 'nic', {

unique: true

});

};

3. Insert data into the object store

Once a connection is opened to the database, the data can be managed inside the onsuccess event handler. Inserting data happens in 4 steps.

function insertUser(db, user) {

// Create a new transaction

const txn = db.transaction('User', 'readwrite');



// Get the UserDetails object store

const store = txn.objectStore('UserDetails'); // Insert a new record

let query = store.put(user);



// Handle the success case

query.onsuccess = function (event) {

console.log(event);

};



// Handle the error case

query.onerror = function (event) {

console.log(event.target.errorCode);

}



// Close the database once the transaction completes

txn.oncomplete = function () {

db.close();

};

}

Once the insertion function is created, the onsuccess event handler of the request can be used to insert more records.

request.onsuccess = (event) => {

const db = event.target.result; insertUser (db, {

email: 'john.doe@outlook.com',

firstName: 'John',

lastName: 'Doe',

}); insertUser (db, {

email: 'ann.doe@gmail.com',

firstName: 'Ann',

lastName: 'Doe'

});

};

There are many operations that can be performed on the IndexedDB. Some of them are as follows.

Read/search data from object stores by key

Read/search data from object stores by index

Update data of a record

Delete a record

Migrate from a previous version of a database, etc.

If you need insights about how to achieve the above, let me know in the comments section below. You can refer here for more information.

Features of Indexed DB

Indexed DB provides many special features that no other browser storage can achieve. Some of the features are briefly explained below.

Has an asynchronous API

This enables performing costly operations without blocking the UI thread and provides a better experience to users

Supports transactions for reliability

If one step fails, the transaction will be canceled and the database will be rolled back to the previous state.

Supports versioning

You can version your database when you are creating it and upgrade the version when needed. Migrating from old versions to new versions is also possible in IndexedDB.

Private to domain

A database is private to a domain, therefore any other site cannot access another website’s IndexedDB stores. This is also called the Same-origin Policy.

Limitations of IndexedDB

So far, IndexedDB seems promising for client-side storage. However, there are few limitations worth noticing.

Even though it has modern browser support, browsers such as IE does not have complete support for this.

Firefox disables IndexedDB completely, in private browsing mode — This can cause your application to malfunction when accessed via an incognito window.

Is IndexedDB right for your application?

Based on the many features provided by IndexedDB, the answer to this million-dollar question could be Yes! However, before jumping to a conclusion, ask yourself the following questions.

Does your application require offline access?

Do you need to store a large amount of data on the client-side?

Do you need to quickly locate/search data in a large set of data?

Does your application access the client-side storage using the supported browsers by IndexedDB?

Do you need to store various types of data including JavaScript objects?

Does writing/reading from client-side storage need to be non-blocking?

If the answer to all of the above questions is Yes, IndexedDB is the best option for you. But if such functionality is not required, you might as well choose a storage method such as localStorage because it provides widespread browser adoption and features an easy-to-use API.

Summary

When we consider all the client-side storage mechanisms, IndexedDB is a clear winner. Let’s look at a summarized comparison of different client-side storage methods.

Hope you got a clear understanding of IndexedDB and its benefits. Let us know your thoughts too.