Take a closer look at the IndexedDB API and its use in practice.

Have you ever heard of a NoSQL database on a browser?

IndexedDB is a large NoSQL storage system. It lets you store almost anything in the user’s browser. In addition to the usual search, fetch, and place operations, IndexedDB also supports transactions.

You can find an example of IndexedDB below.

In this article, we will focus on the following.

  • Why do we need IndexedDB?
  • How do we use IndexedDB in our applications?
  • The function of with IndexedDB
  • Limitations of IndexedDB
  • Is IndexedDB suitable for your application?

Why do we need IndexedDB?

IndexedDB is considered more powerful than localStorage!

Do you know the reason behind it? Let’s find out.

Can store much larger amounts of data than localStorage

There are no special restrictions such as localStorage (between 2.5MB and 10MB). The maximum limit depends on the browser and disk space. Chrome and Chromium-based browsers, for example, allow up to 80% disk space. If you have 100GB, IndexedDB can use up to 80GB of space and a single Origin can use up to 60GB. Firefox allows up to 2GB per Origin, while Safari allows up to 1GB per source.

You can store any type of value based on {key: value} pairs

More flexibility to store different data types. This means not only strings, but also binary data (ArrayBuffer objects, Blob objects, etc.). It uses object storage to store data internally.

Provide a search interface

This is not available in other browser storage options, such as localStorage and sessionStorage.

Useful for Web applications that do not require a continuous Internet connection

IndexedDB is useful for both online and offline working applications; for example, it can be used for client-side storage in progressive Web applications (PWA).

Application state can be stored

You can greatly improve application performance by storing application state for frequent users. Later, the application can be synchronized with the back-end server and updated through lazy loading.

Let’s look at the structure of IndexedDB, which can store multiple databases.

The structure of with IndexedDB

How do we use IndexedDB in our applications?

In the following sections, we’ll look at how to use IndexedDB to bootstrap the application.

1. Use window.indexedDB to open the database connection

const openingRequest = indexedDB.open('UserDB'.1);
Copy the code

In this case, UserDB is the database name and 1 is the database version. This returns an object that is an instance of the IDBOpenDBRequest interface.

2. Create object storage

When a database connection is opened, onUpgradenneeded events are triggered which can be used to create object stores.

// Create the UserDetails object repository and index
request.onupgradeneeded = (event) = > {
  let db = event.target.result;

  // Create the UserDetails object store
  // Has an auto-incrementing ID
  let store = db.createObjectStore('UserDetails', {
    autoIncrement: true
  });

  // Create an index on the NIC attribute
  let index = store.createIndex('nic'.'nic', {
    unique: true
  });
};
Copy the code

3. Insert data into the object store

Once the connection to the database is open, the data can be managed in the onSuccess event handler. Inserting data occurs in four steps.

function insertUser(db, user) {
  // Create a new thing
  const txn = db.transaction('User'.'readwrite');

  // Get the UserDetails object store
  const store = txn.objectStore('UserDetails');
  // Insert new record
  let query = store.put(user);

  // Handle the success case
  query.onsuccess = function (event) {
    console.log(event);
  };

  // Handle the failed use case
  query.onerror = function (event) {
    console.log(event.target.errorCode);
  }

  // Close the database after the transaction is complete
  txn.oncomplete = function () {
    db.close();
  };
}
Copy the code

Once the insert function is created, the requested onSuccess event handler can be used to insert more records.

request.onsuccess = (event) = > {
   const db = event.target.result;
   insertUser(db, {
     email: '[email protected]'.firstName: 'John'.lastName: 'Doe'}); insertUser(db, {email: '[email protected]'.firstName: 'Ann'.lastName: 'Doe'
   });
};
Copy the code

There are many operations that can be performed on IndexedDB, some of which are as follows:

  • Read/search data from the object store by key
  • Read/search data from the object store by index
  • Update recorded data
  • Delete records
  • Migration from a previous version of the database, etc

The function of with IndexedDB

IndexedDB provides a number of special features that are not available in other browser stores, some of which are briefly described below.

Have asynchronous APIS

This enables expensive operations to be performed without blocking the UI thread and provides a better experience for the user.

Support transactions to ensure reliability

If one step fails, the transaction is cancelled and the database is rolled back to its previous state.

Support for version control

You can version control the database as it is created and update it as needed. It is also possible to migrate from an old version to a new version in IndexedDB.

Private domain

The database is a domain private database, so no other web site can access another web site’s IndexedDB storage. This is known as the same origin policy.

Limitations of IndexedDB

So far, IndexedDB seems promising for client-side storage. However, there are some notable limitations.

  • Even if modern browsers support it, browsers like Internet Explorer don’t fully support it.
  • Firefox completely disables IndexedDB in private browsing mode – this may cause your application to fail when accessed through an invisible window.

Is IndexedDB suitable for your application?

Based on the many features that IndexedDB offers, the answer to this million-dollar question is probably Yes! However, before jumping to conclusions, ask yourself the following questions.

  • Does your application need offline access?
  • Do you need to store a lot of data on the client?
  • Do you need to quickly find/search data in large amounts of data?
  • Does your application use a browser supported by IndexedDB to access client storage?
  • Do you need to store various types of data, including JavaScript objects?
  • Does writing/reading from client storage need to be non-blocking?

If you answered “yes” to all of the above questions, IndexedDB is your best bet. But if you don’t need such functionality, you might as well opt for a storage method like localStorage, which provides a wide range of browser applications and has an easy-to-use API.

conclusion

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

Cookies Web Storage IndexedDB
storage A small query table with key and data-value pairs Only characters

String key, value storage
Object storage, which can store any type of data, including objects
capacity 4KB 5MB-25MB More than 50 MB
The index Does not support Does not support support
API call types synchronous synchronous asynchronous
Operating performance Direct execution Direct execution The transaction
The learning curve low low high

Hopefully you have a clear idea of IndexedDB and its benefits.


Translated from blog.bitsrc. IO by Viduni Wickramarachchi