Advanced Storage

IndexedDB

Build powerful offline applications with IndexedDB - a low-level API for client-side storage of significant amounts of structured data.

What is IndexedDB?

IndexedDB is a browser database for storing large amounts of structured data, including objects, files and blobs, with indexes for fast lookups. It's asynchronous and transactional, and it's what offline-capable web apps and PWAs use for local data. Its raw API is verbose, so most developers use a small wrapper such as idb or Dexie.

import { openDB } from "idb";
const db = await openDB("notes", 1, {
  upgrade(db) { db.createObjectStore("notes", { keyPath: "id" }); },
});
await db.put("notes", { id: 1, text: "Hello" });
const note = await db.get("notes", 1);

Key Features

Asynchronous

Non-blocking operations with promises

Indexable

Fast searches with indexes

Transactional

ACID compliance for data integrity

Interactive IndexedDB Demo

Experience full CRUD operations with IndexedDB including database initialization, data management, and advanced features.

IndexedDB Architecture

Database Structure

  • Database: Top-level container
  • Object Store: Like a table
  • Index: Secondary keys for searching
  • Transaction: Unit of work
  • Cursor: Iterator for data

Key Features

  • Asynchronous: Non-blocking operations
  • Transactional: ACID compliance
  • Event-driven: Success/error callbacks
  • Same-origin: Domain-specific data
  • Persistent: Data survives browser restart

Core Database Operations

Database Creation & Setup

Initialize database with version control and schema definition:

const request = indexedDB.open('MyDB', 1); request.onupgradeneeded = (event) => { const db = event.target.result; // Create object store const store = db.createObjectStore('users', { keyPath: 'id', autoIncrement: true }); // Create indexes store.createIndex('email', 'email', { unique: true }); store.createIndex('name', 'name', { unique: false }); };

Transaction Management

Transaction Types
  • readonly - Read operations only
  • readwrite - Read and write operations
  • versionchange - Schema modifications
Transaction Lifecycle
const tx = db.transaction(['users'], 'readwrite'); const store = tx.objectStore('users'); store.add(data);

CRUD Operations

Create & Update
// Add new record store.add(data); // Update existing record store.put(data);
Read & Delete
// Get single record store.get(key); // Delete record store.delete(key);

Advanced IndexedDB Features

Indexes & Complex Queries

Index Creation
// Simple index store.createIndex('name', 'name'); // Compound index store.createIndex('fullName', ['firstName', 'lastName']);
Range Queries
// Key range const range = IDBKeyRange.bound(18, 65); index.openCursor(range);

Cursors for Data Iteration

Efficiently iterate through large datasets:

const request = store.openCursor(); request.onsuccess = (event) => { const cursor = event.target.result; if (cursor) { console.log(cursor.value); cursor.continue(); // Move to next } };

Key Ranges & Filtering

Bounded Range
IDBKeyRange.bound( 'A', 'D', false, true )
Lower Bound
IDBKeyRange.lowerBound( 18, false )
Upper Bound
IDBKeyRange.upperBound( 65, true )

Performance & Best Practices

Performance Optimization

  • • Use indexes for frequent queries
  • • Batch operations in single transaction
  • • Limit cursor iteration ranges
  • • Close transactions promptly
  • • Avoid blocking the main thread

Schema Design

  • • Plan schema before implementation
  • • Use appropriate key paths
  • • Consider data relationships
  • • Normalize vs denormalize trade-offs
  • • Version control for migrations

Error Handling

  • • Always handle onerror events
  • • Check browser support
  • • Implement graceful degradation
  • • Handle quota exceeded errors
  • • Provide user feedback

Security Considerations

  • • Same-origin policy enforcement
  • • No encryption at rest
  • • Validate all input data
  • • Consider data sensitivity
  • • User can clear data anytime

Real-World Applications & Use Cases

Offline-First Applications

  • • Progressive Web Apps (PWAs)
  • • Note-taking applications
  • • Email clients with offline sync
  • • Document editors
  • • Task management tools

Data-Heavy Applications

  • • Media libraries and galleries
  • • Scientific data visualization
  • • Financial trading platforms
  • • Gaming save states
  • • Analytics dashboards

Performance Optimization

  • • API response caching
  • • Image and asset storage
  • • Search index creation
  • • Prefetched content storage
  • • User preference persistence

Complex Data Management

  • • Customer relationship management
  • • Inventory management systems
  • • Project management tools
  • • Content management systems
  • • Collaborative editing platforms

Code Editor

<input id="note" placeholder="Write a note">
<button id="add">Save note</button>
<ul id="notes"></ul>

Preview

IndexedDB — step by step

1 / 4
1

Open a database

Use indexedDB.open('dbName', version) to open or create a database. The onupgradeneeded event fires when the database is first created or when the version number increases, which is where you define object stores.

1 of 4
🔍IndexedDB Is Powerful but Complex
Unlike localStorage, IndexedDB can store structured objects, binary data, and large datasets. It supports indexes for fast querying and can hold hundreds of megabytes. The API is verbose — libraries like Dexie.js or idb wrap it in a cleaner Promise-based interface for real-world use.

🎯 Quick Check

Where in IndexedDB do you create object stores?

IndexedDB: summary

Key points

  • Storage limits are much larger than localStorage, often a percentage of free disk space.
  • Schema changes happen in the upgrade callback when you increase the version number.
  • Data is per origin and can be evicted under storage pressure unless you call navigator.storage.persist().

Frequently asked questions

›When should I use IndexedDB instead of localStorage?

When you store more than a few kilobytes, need queries or indexes, store files or blobs, or need non-blocking async access.