latentspace.

IndexedDB


  • What is IndexedDB
    • A client-side NoSQL database built into the browser
    • Unlike localStorage, it can store large amounts of structured data (objects, files, Blobs, etc.)
    • Stores data in key-value format and supports fast lookups via indexes
    • A Web API standard — available in all modern browsers without any installation

  • Differences from localStorage / sessionStorage
    • localStorage: stores strings only, ~5-10MB max, synchronous API
    • sessionStorage: similar to localStorage but scoped per tab — data is deleted when the tab/window closes
    • IndexedDB: can store objects, hundreds of MB or more, asynchronous API
    • IndexedDB operates on a transaction-based model, ensuring data integrity

  • Where the data is stored
    • Data is stored on the user's local disk, managed internally by the browser engine
    • Under the hood, most browsers use LevelDB (Chrome) or SQLite (Firefox, Safari) as the backing storage engine — but this is an implementation detail, not exposed to the API
    • Storage paths by browser:
      • Chrome (Linux): ~/.config/google-chrome/Default/IndexedDB/
      • Chrome (macOS): ~/Library/Application Support/Google/Chrome/Default/IndexedDB/
      • Chrome (Windows): %LOCALAPPDATA%\Google\Chrome\User Data\Default\IndexedDB\
      • Firefox: ~/.mozilla/firefox/<profile>/storage/default/
      • Safari: ~/Library/Containers/com.apple.Safari/Data/Library/WebKit/WebsiteData/Default/
    • Inside these directories, data is organized by origin — e.g. https_example.com_0.indexeddb.leveldb/
    • Isolated per origin (protocol + domain + port) — cannot access data from other origins (Same-Origin Policy)
    • The files on disk are not human-readable — they are binary database files managed by LevelDB/SQLite, not plain JSON or text
    • Storage quota:
      • Chrome: up to 60% of total disk space per origin (within an overall browser limit of 80% of disk)
      • Firefox: up to 10% of total disk space per origin (or 10 GiB group limit, whichever is smaller)
      • Safari (17.0+): up to 60% of total disk space per origin (overall 80% of disk, same as Chrome)
    • Check available storage programmatically:
      
          const estimate = await navigator.storage.estimate();
          console.log(`Used: ${estimate.usage} bytes`);
          console.log(`Quota: ${estimate.quota} bytes`);
      
    • Data persistence:
      • By default, the browser may evict IndexedDB data under storage pressure (low disk space) — this is called "best-effort" persistence
      • Request persistent storage to prevent eviction: await navigator.storage.persist()
      • Deleted when the user clears browser data, or at session end in incognito/private mode

  • Core concepts
    • Database: the top-level container, identified by name and version
    • Object Store: equivalent to a table in RDBMS — the actual storage space for data
    • Key: a value that uniquely identifies each record, configured via keyPath or autoIncrement
    • Index: a secondary key for fast lookups on a specific property
    • Transaction: all read/write operations run inside a transaction — three modes: readonly, readwrite, versionchange
    • Cursor: a mechanism for iterating over records in an Object Store

  • How it works (basic flow)
    1. Open a database — indexedDB.open(name, version)
      
          const request = indexedDB.open("MyDatabase", 1);
      
    2. Set up the schema — create Object Stores and Indexes in the onupgradeneeded event
      
          request.onupgradeneeded = (event) => {
              const db = event.target.result;
              const store = db.createObjectStore("users", { keyPath: "id" });
              store.createIndex("name", "name", { unique: false });
          };
      
    3. Write data — open a transaction and add data to the Object Store
      
          request.onsuccess = (event) => {
              const db = event.target.result;
              const tx = db.transaction("users", "readwrite");
              const store = tx.objectStore("users");
              store.add({ id: 1, name: "Park", age: 30 });
          };
      
    4. Read data — query by key or index
      
          const tx = db.transaction("users", "readonly");
          const store = tx.objectStore("users");
          const getRequest = store.get(1);
          getRequest.onsuccess = () => {
              console.log(getRequest.result); // { id: 1, name: "Park", age: 30 }
          };
      

  • Async patterns
    • The IndexedDB API is event-driven — every request requires onsuccess and onerror callbacks
    • Wrapping with Promises enables the async/await pattern
    • idb library: a lightweight wrapper that provides a Promise-based API for IndexedDB
      
          import { openDB } from "idb";
      
          const db = await openDB("MyDatabase", 1, {
              upgrade(db) {
                  db.createObjectStore("users", { keyPath: "id" });
              },
          });
      
          await db.add("users", { id: 1, name: "Park", age: 30 });
          const user = await db.get("users", 1);
      

  • Use cases
    • Offline web apps: caching data offline alongside Service Workers
    • Large client-side data: storing images, files, large JSON payloads in the browser
    • Client-side search: fast local search using indexes
    • Persistent state: preserving app state across refreshes and reconnections

  • Things to watch out for
    • No synchronous API — all operations are async, requiring callbacks or Promises
    • Schema migration — onupgradeneeded fires on initial database creation or when the version number is incremented. Be careful with version management when modifying existing Object Stores
    • Storage Quota — storage limits vary by browser. Use navigator.storage.estimate() to check available capacity
    • Debugging — inspect and edit data in Chrome DevTools > Application > IndexedDB