Browser InternalsIntermediate
You know localStorage, but do you know IndexedDB?
What is IndexedDB?
IndexedDB is a built-in browser NoSQL database that lets the front end store large amounts of structured data locally (JS objects, Blobs, files…) with support for indexes, transactions, and asynchronous operations.
localStorage vs IndexedDB
| Feature | localStorage | IndexedDB |
|---|---|---|
| Data types | String key-value pairs | Any JS object (incl. Blob, File) |
| Capacity | ~5–10 MB | Usually ≥ 250 MB (device-dependent) |
| Access | Synchronous | Asynchronous (events / Promises) |
| Indexes / queries | None | Yes (create indexes) |
| Transactions | None | Yes (ACID) |
| Best for | Small config values | Large data, offline apps (PWA) |
Core concepts
- Database — the top-level container, identified by name + version number
- Object Store — similar to an SQL table; stores objects
- Index — an index on an object property that speeds up queries
- Transaction — all reads and writes happen inside a transaction, ensuring consistency
- Cursor — used to iterate over large datasets
Basic usage (native API)
// Open the database
const request = indexedDB.open('myDB', 1);
request.onupgradeneeded = (e) => {
const db = e.target.result;
const store = db.createObjectStore('users', { keyPath: 'id' });
store.createIndex('name', 'name', { unique: false });
};
request.onsuccess = (e) => {
const db = e.target.result;
// Write (readwrite transaction)
const tx = db.transaction('users', 'readwrite');
tx.objectStore('users').add({ id: 1, name: 'Alice', age: 30 });
// Read (readonly transaction)
const tx2 = db.transaction('users', 'readonly');
const getReq = tx2.objectStore('users').get(1);
getReq.onsuccess = () => console.log(getReq.result);
};
Promise wrapper — use the idb library
The native API is event-driven and verbose. The idb library (by Jake Archibald) wraps it in a clean Promise API:
import { openDB } from 'idb';
const db = await openDB('myDB', 1, {
upgrade(db) {
db.createObjectStore('users', { keyPath: 'id' });
},
});
await db.put('users', { id: 1, name: 'Alice', age: 30 });
const user = await db.get('users', 1);
console.log(user); // { id: 1, name: 'Alice', age: 30 }
Common use cases
- PWA offline cache — cache API responses and large assets
- Draft auto-save — article drafts, multi-step form progress
- Client-side pagination — sort and filter large datasets without a server round-trip
- Offline-first applications
Summary
When choosing browser storage:
- Need to store more than a few MB → IndexedDB
- Need complex structures, querying, or indexing → IndexedDB
- Simple key-value config, small size → localStorage
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
