IndexedDB Support for Client-Side Database Storage
Detect IndexedDB support for storing large amounts of structured data in the browser. Covers database operations, transactions, and storage quota.
Storage
Detailed Explanation
IndexedDB Detection
IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files and blobs. It is the primary choice for offline data storage in web applications.
Detection
const hasIndexedDB = typeof indexedDB !== 'undefined';
Opening a Database
function openDB(name, version) {
return new Promise((resolve, reject) => {
const request = indexedDB.open(name, version);
request.onupgradeneeded = (event) => {
const db = event.target.result;
if (!db.objectStoreNames.contains('items')) {
const store = db.createObjectStore('items', {
keyPath: 'id',
autoIncrement: true,
});
store.createIndex('name', 'name', { unique: false });
}
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
CRUD Operations
async function addItem(db, item) {
const tx = db.transaction('items', 'readwrite');
tx.objectStore('items').add(item);
return new Promise((resolve, reject) => {
tx.oncomplete = resolve;
tx.onerror = () => reject(tx.error);
});
}
async function getItem(db, id) {
const tx = db.transaction('items', 'readonly');
const request = tx.objectStore('items').get(id);
return new Promise((resolve) => {
request.onsuccess = () => resolve(request.result);
});
}
Storage Comparison
| Storage | Capacity | Sync/Async | Structured | Indexed |
|---|---|---|---|---|
| localStorage | ~5MB | Sync | No (strings) | No |
| sessionStorage | ~5MB | Sync | No (strings) | No |
| IndexedDB | 50%+ of disk | Async | Yes | Yes |
| Cache API | 50%+ of disk | Async | HTTP responses | By URL |
Storage Quota
if (navigator.storage && navigator.storage.estimate) {
const { usage, quota } = await navigator.storage.estimate();
console.log(\`Using \${usage} of \${quota} bytes\`);
}
Browsers typically allow 50% or more of available disk space. Use navigator.storage.persist() to prevent eviction of important data.
Use Case
Powers offline-first applications, client-side caching of API responses, storing user-generated content before sync, managing large datasets (e.g., email clients, note-taking apps), and persisting application state across sessions.