JavaScript IndexedDB
IndexedDB is a low-level client-side database that allows large amounts of structured data to be stored in the browser. It is asynchronous, transactional, and supports key-value storage.
1. Why Use IndexedDB?
✅ Stores large amounts of data (better than localStorage
).
✅ Works offline and persists data.
✅ Supports transactions, indexes, and queries.
✅ Asynchronous and non-blocking.
2. Basic IndexedDB Workflow 🛠️
Step 1: Open (or Create) a Database
🔹 indexedDB.open("MyDatabase", 1)
– Opens the database (version 1
).
🔹 onupgradeneeded
– Runs once when a new database or version is created.
🔹 createObjectStore("users")
– Creates a table-like store with id
as the primary key.
Step 2: Add Data
🔹 Uses transaction("users", "readwrite")
to add data.
🔹 store.add(user)
adds a new entry.
🔹 Runs onsuccess
or onerror
callbacks.
Step 3: Read Data
🔹 Uses store.get(id)
to fetch data.
Step 4: Update Data
🔹 Uses store.put(user)
to update existing data.
Step 5: Delete Data
🔹 Uses store.delete(id)
to remove an entry.
Step 6: Fetch All Data
🔹 Uses store.openCursor()
to loop through all records.
7. Using Indexes for Searching 🔎
Indexes improve search performance for non-primary key fields.
Add an Index
Modify onupgradeneeded
:
Search by Name
🔹 Uses .createIndex("name", "name")
to create an index.
🔹 Uses index.get(name)
to search for a user by name.
8. Deleting the Database
🔹 Removes the entire database from the browser.
9. IndexedDB vs Other Storage Methods
Feature | IndexedDB | localStorage | sessionStorage | Web SQL (Deprecated) |
---|---|---|---|---|
Data Size | Large (MBs/GBs) | 5MB | 5MB | Large |
Structure | Object Store | Key-Value | Key-Value | Tables |
Asynchronous? | ✅ Yes | ❌ No | ❌ No | ✅ Yes |
Indexed Queries? | ✅ Yes | ❌ No | ❌ No | ✅ Yes |
Transactions? | ✅ Yes | ❌ No | ❌ No | ✅ Yes |
Works Offline? | ✅ Yes | ✅ Yes | ❌ No | ✅ Yes |
Conclusion 🎯
✅ IndexedDB is perfect for storing large, structured data in the browser.
✅ Supports transactions, indexes, and queries.
✅ Asynchronous, so it does not block the UI.
✅ Can store JSON objects instead of simple strings.
💡 Need help implementing IndexedDB in your project? Let me know!