Matthew Setter is a professional technical writer and passionate web application developer. He’s also the founder of Malt Blue, the community for PHP web application development professionals and PHP Cloud Development Casts – learn Cloud Development through the lens of PHP. You can connect with him on TwitterFacebookLinkedIn or Google+ anytime.

Local_ and SessionStorage provide a much more efficient way of storing information client-side in the browser. What’s more, they don’t have the overhead that Cookies do since they aren’t included with page requests. We looked at how it works, potential security implications, browser support and more.

But Local- and SessionStorage aren’t the only available options when we’re looking to increase the complexity of the web applications that we develop and deliver today. With HTML5, the W3C provides another standard that may be more of what you’re looking for, especially if you’re a fan of the NoSQL based technologies. This option is IndexedDB.

So in this article, we’re going to look at what IndexedDB is, what its advantages and disadvantages are, and where it would be a good fit for your development needs. In the next installment, we’ll finish off with a sample application so you can get a hands on understanding of how it works.

What is IndexedDB

IndexedDB is an alternative to the (now deprecated) W3C standard WebSQL Database (WebSQL). It was introduced around April 23, 2009. This is a description from Wikipedia:

“… is a web page API for storing data in databases that can be queried using a variant of SQL”

As it says on the tin, WebSQL brings client-side application development the full power of SQL. Based on SQLite, it allows us to employ one of the fundamental skills we have in our development toolkit -- database development -- both on the client and the server side.

On November 18, 2010, the W3C made the decision to no longer support the standard. This was due to disagreement from a number of vendors -- including Mozilla and Microsoft -- on how it should be practically implemented and incomplete browser support. As a result, IndexedDB was introduced as an alternative standard for web data storage.

IndexedDB best practices

However, IndexedDB is not a browser database but an Object Store. It allows for applications to design, store and manipulate objects, without sterilization, and the ability to conduct high performance searches on them.

As I mentioned earlier, it's a lot like NoSQL databases, such as mongoDB and CouchDB. Objects are created and manipulated in JavaScript, and then stored and updated in the object store.

But it's not exactly the same as say a standard PHP, Ruby or Python script creating and persisting objects. There are a few key points to know and remember when using it

Operations Require Transactions

Every operation that you perform when using IndexedDB must be carried out within a transaction. Whether that's reading information from an object store, manipulating data in it or changing its structure.

Transactions can have three modes:

Mode

Description

readonly (snapshot) Be able to read object stores of the database without being able to change anything.
readwrite Be able to read and write object stores in the database, without being able to change its structure.
versionchange Be able to change the structure of, add and remove object stores in a database along with managing indexes on them.

Operations are Ashynchronous

Here’s the difference. With SQL, you run a query and receive back the result. With IndexedDB, you run a transaction and set up a callback to handle the success or failure of the transaction, which you can check in on later. You don't fire off the request and wait for the result, such as retrieving a list of objects matching an index.

If you're familiar with jQuery, you'll know what I'm referring to. If not, have a look at the following code:

var jqxhr = $.ajax("http://www.newrelic.com")

  .done(function() { alert("success"); })

  .fail(function() { alert("error"); })

  .always(function() { alert("complete"); });

With the code above, we're making an ajax request to newrelic.com. We then setup three handlers or callbacks; one for the done, fail and always events. We also do this in IndexedDB. Have a look at the sample below:

// open the library data store

var request = indexedDB.open("library");



request.onsuccess = function(e) {

  newrelic.indexedDB.getAllbooksList();

};



request.onerror = function(e) {

  console.log("Error Opening Object Store. : ", e);

};

Here we make a request to open the library datastore. If the request is successful, we fire off the getAllbooksList function, which in turn, follows a similar pattern. If the request fails, we log the reason why.

Indexes & Cursors

Continuing the database analogy, objects in the object store can have one or a collection of indexes to speed up data retrieval. Creating them is rather simple, as shown in this code from the Mozilla Development Network (MDN):

// This is what our customer data looks like.

const customerData = [

{ ssn: "444-44-4444", name: "Bill", age: 35, email: "bill@company.com" },

{ ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org" }

];



// Create an objectStore to hold information about our customers. We're

// going to use "ssn" as our key path because it's guaranteed to be

// unique.

var objectStore = db.createObjectStore("customers", { keyPath: "ssn" });



// Create an index to search customers by name. We may have duplicates

// so we can't use a unique index.

objectStore.createIndex("name", "name", { unique: false });

With cursors, we are able to iterate over the data that we retrieve from the object store. We can also use an index to limit the data that we retrieve. In the example below, also from MDN, we perform a ‘getall’ type query:

var customers = [];



objectStore.openCursor().onsuccess = function(event) {

  var cursor = event.target.result;

  if (cursor) {

    customers.push(cursor.value);

    cursor.continue();

  }

  else {

    alert("Got all customers: " + customers);

  }

};

Browser Support

IndexedDB is supported by almost every browser.

Browser

Version

Mozilla Firefox

106

Google Chrome

107

IE version

11

Although IE doesn't fully support IndexedDB, that's not too concerning as Microsoft ended support on most versions of Windows 10 as of June 2022. As WebSQL is deprecated, it's likely that support for IndexedDB will continue to grow over time as the spec becomes more refined. To find out exactly which browsers (and their versions) support it, try it out at caniuse.com.

Although Safari, Chrome and Opera still support WebSQL -- and technically you could develop apps with it -- it’s not a good idea to do so. Some, however, suggest a middle ground with the use of a wrapper library allowing you to have the both of best worlds.

Advantages

1. An emerging standard

With lots of support from the W3C, Mozilla, Microsoft and Google, IndexedDB is rapidly emerging as a standard. It is likely that it will be around for quite some time, meaning you can reliably develop against it. What’s more, it offers a sense of stability and vendor independence that WebSQL does not.

IndexedDB is also often chosen by developers as it doesn’t block the DOM when used with a worker ().

Finally, IndexedDB is a great choice for storing high volumes of data. It has both a synchronous and asynchronous API, so it won’t block the user interface from loading, and it provides indexes.

2. Use objects – Not SQL

Additionally, Indexed DB lets you work with objects as best suits the needs and designs of your application (whereas WebSQL required that you had a solid grasp of SQL.)

Disadvantages

1. Lack of browser support

Historically, browser support was a major hurdle for IndexedDB. However, according to Lambdatest, IndexedDB actually scores a fairly high score on browser support in the modern age. At a 93, it has high compatibility with Edge, Firefox, Chrome, Safari, iOS, and Android

2. Lack of speed

The major issue that developers see with IndexedDB is speed. Using something like localStorage (Web Storage) would in theory work very quickly. However, that’s only true with small amounts of data. Since localStorage is a synchronous API it would be slowed down with larger amounts of data.

Use cases for IndexedDB

As I've alluded to, IndexedDB is a good fit if your client-side data needs are more complex than what Local/SessionStorage can provide (i.e. you're looking for more than a simple Key/Value store in your application) and if you are dealing with large amounts of data.

Yes, you can use JavaScript functions (such as JSON.stringify and JSON.parse) to manage information stored in it. But it doesn't offer you the flexibility and power that IndexedDB does. So if you want a storage layer that offers higher performance, duplicate key values or an efficient way to search through the data stored, then go with IndexedDB. But if your needs are simpler, then go with Session and LocalStorage. Remember, your needs are what should guide your choice.

IndexedDb vs localStorage vs WebSQL

There’s been a lot of debate for and against WebSQL and IndexDB. Personally, I don’t see WebSQL as a bad technology, but I see IndexedDB as a better choice. These three points for IndexedDB sums up why I think it’s a better choice:

  • SQL is an entirely different system, unrelated to the languages it’s usually embedded within.
  • It's easy for inexperienced programmers to embed security flaws in their SQL statement
  • It's easy for inexperienced programmers to develop overly complex queries that database systems find impossible to process in a reasonable period of time

Web applications are getting ever more complex, and it's not right to take a technology that predated the web and attempt to retro-fit it into it. I believe the better choice is to split from the past and to provide a data storage layer that is more appropriate to its needs. And this is what I believe IndexedDB is.

Additionally, Web SQL is a more dated approach, and has not been deprecated since November 2010, which limits browser support significantly.

As far as localStorage goes, I already covered that it can be the right choice for smaller, less-complicated amounts of data. However, for larger and complex data sets, IndexedDB still takes the lead.

Conclusion

So there you have it. IndexedDB is the new standard for client-side data storage. It allows us to store complex objects that we create and manipulate in JavaScript combined with a decent amount of index performance when searching for the information stored.

We've looked at the advantages and disadvantages and touched on whether it or WebSQL is the right standard for the future. So what do you think about it? Do you believe it's the right fit for the future of web application development? Or do you believe that WebSQL would have been the better choice? Voice your opinion in the comments. We want to know what you think.

Further Reading