DEV Community

Cover image for Client-side data storage with IndexedDB

Posted on • Updated on

Client-side data storage with IndexedDB

IndexedDB is a well sophisticated database for persisting data in a user's browser.
Although, there are other storage options like localStorage or Cookies, they are rather limited and cannot handle complex data types.

In this article, we'll delve into what IndexedDB is and its key features, so get ready to learn something new today.

What is IndexedDB?

IndexedDB is a client side database for
storing data directly in the the browser. It is based on the same origin policy, meaning that web pages of different domains cannot access the same IndexedDB database.

An IndexedDB Database is simply a collection of object stores.

So called object stores as their name implies are the storage of IndexedDB. It is where the actual data is stored. An IndexedDB database may have multiple object stores.

An object store holds records which are key πŸ—οΈ-value pairs. The keys of an object store can be a string, date, float, a binary blob, or an array.

Objects that can be stored must support the structured clone algorithm.

Haven't heard of the structured clone algorithm πŸ€”?

The structured clone algorithm is a mechanism that JavaScript engines use when copying objects using certain APIs. These objects can be arrays, maps, sets, objects and other built-in JavaScript data types (with the exception of functions, DOM nodes and Error objects).

The IndexedDB API uses many requests for its operation. What do I mean?

An IndexedDB API usage can happen in these steps:

  • You send a request to open a connection to the database. This request can either fail or succeed, so you can add event listeners πŸ‘‚ to the success event.

  • Inside the success event handler, you create a transaction, get an object store from the transaction, then add or delete data to the object store.

Note: every attempt to add, delete or update data in an IndexedDB database object store must be wrapped 🎁 in a transaction 😲.

Now, what is a transaction?

A transaction is a group of operations to be performed on a database that should either all succeed or all fail. If you’re doing a lot of writes to an object store, it’s much faster if they happen in one transaction.

This is just the surface level of the IndexedDB API ad want it can do.

If you would like me to explain more about IndexedDB and other client-side storage options, you can tell me in the comments.

Image credits: Matt Anderson

Do like πŸ‘ and follow πŸƒ for more content.

Top comments (1)

michthebrandofficial profile image

Here is my Twitter handle, if you have any questions:

DMs are always open 😊