Skip to content

What is IndexedDB

Key idea:

IndexedDB — a browser-built-in NoSQL database storing structured data (records, blobs, files) on the client. Async API, transactional, supports indexes, 100+ MB storage. Used in PWAs for offline-first + large-volume cache. Replaces deprecated WebSQL. Alternatives: localForage (wrapper), Dexie.js (ORM-like).

Below: details, example, related terms, FAQ.

Check your site →

Details

  • Object stores (= collections): organize records by keyPath
  • Transactions: readonly / readwrite / versionchange
  • Indexes: secondary keys for efficient queries
  • Storage quota: ~20-60% of free disk (Chrome), ~1GB (Safari)
  • Eviction: browser may clear when space is low

Example

const request = indexedDB.open('myDB', 1);
request.onupgradeneeded = e => {
  e.target.result.createObjectStore('users', { keyPath: 'id' });
};
request.onsuccess = e => {
  const tx = e.target.result.transaction('users', 'readwrite');
  tx.objectStore('users').put({ id: 1, name: 'Alice' });
};

Related Terms

How to Use IndexedDB: Basic Operations

IndexedDB provides a powerful API for storing and retrieving large amounts of structured data. Here are the basic operations to get you started:

  • Opening a Database: You can open a database using the indexedDB.open() method.
const request = indexedDB.open('myDatabase', 1);

In this example, 'myDatabase' is the name of your database, and '1' is the version number. You can also handle the onupgradeneeded event to create object stores:

request.onupgradeneeded = function(event) {
const db = event.target.result;
db.createObjectStore('myStore', { keyPath: 'id' });
};
  • Adding Data: Use a transaction to add data to your object store.
const transaction = db.transaction('myStore', 'readwrite');
const store = transaction.objectStore('myStore');
store.add({ id: 1, name: 'Item 1' });

In this example, we're adding an object with an id and name to the 'myStore' object store.

  • Retrieving Data: You can retrieve data using the get() method.
const getRequest = store.get(1);
getRequest.onsuccess = function(event) {
console.log(event.target.result);
};

This retrieves the object with id 1 from the store.

IndexedDB allows for complex queries and transactions, making it suitable for applications requiring a significant amount of client-side data management.

IndexedDB vs. Other Client-Side Storage Options

When it comes to client-side storage, IndexedDB is not the only option available. Here, we compare IndexedDB with other popular storage solutions:

  • LocalStorage: LocalStorage is a simple key-value store. It is synchronous and has a storage limit of around 5-10 MB per origin. Ideal for small amounts of data, LocalStorage is not suitable for applications requiring large datasets or complex queries.
  • SessionStorage: Similar to LocalStorage, SessionStorage offers a key-value storage mechanism but only persists data for the duration of the page session. It is also synchronous and has the same storage limits.
  • WebSQL: WebSQL is a deprecated SQL-based storage solution. While it offered powerful querying capabilities, it has been phased out in favor of IndexedDB due to its lack of support across all browsers.
  • Cookies: Cookies can store small amounts of data but are primarily used for session management and tracking. They are sent with every HTTP request, which can lead to performance issues.

In contrast, IndexedDB supports asynchronous operations, transactions, and large storage limits (over 100 MB). It is designed for applications requiring offline capabilities and the ability to handle complex data structures.

For developers, the choice between these options should be based on the specific needs of the application. IndexedDB is the best choice for applications that require robust data storage and retrieval capabilities, especially in Progressive Web Apps (PWAs).

IndexedDB Best Practices and Performance Tips

When working with IndexedDB, following best practices can enhance performance and ensure a smoother user experience. Here are some key tips:

  • Batching Writes: Instead of writing data one record at a time, batch multiple writes into a single transaction. This reduces the overhead associated with opening and closing transactions.
  • Use Indexes: Create indexes on frequently queried fields. This can significantly speed up read operations. Use the createIndex() method when setting up your object store.
const store = db.transaction('myStore', 'readwrite').objectStore('myStore');
store.createIndex('nameIndex', 'name');

With the above index, you can quickly search for records by name.

  • Handle Errors Gracefully: Always implement error handling for your database operations. Use the onerror event handler to catch and respond to errors appropriately.
request.onerror = function(event) {
console.error('Database error: ' + event.target.errorCode);
};

Clean Up Unused Data: Regularly review and remove outdated or unnecessary data from your database to keep it optimized.

By adhering to these best practices, developers can maximize the efficiency of their applications that utilize IndexedDB, ensuring they run smoothly and effectively even under heavy data loads.

Learn more

Frequently Asked Questions

IndexedDB vs localStorage?

localStorage — 5-10 MB, sync, string-only. IndexedDB — gigabytes, async, structured objects + indexes.

Mobile support?

Yes, every modern browser (Safari iOS, Chrome Android). Safari is partially limited in PWA context.

Eviction — will my data disappear?

When disk space is tight — yes. For critical data use <code>navigator.storage.persist()</code>.

Try the live tool that powered this guide

Free plan — 10 monitors, checks every 5 min, no card required. Upgrade for 1-minute interval and multi-region monitoring.