IndexedDB Storage Adapter
The IndexedDBAdapter extends the abstractStorageAdapterclass, providing a concrete implementation for persisting data to the browser'sIndexedDB. This adapter offers persistent, high-capacity client-side storage with enhanced capabilities including encryption, expiration management, metadata tracking, and optional cross-tab synchronization.
1. Getting Started
Initialize the adapter with the desired options:
import { IndexedDBAdapter } from "storagefy";
const adapter = new IndexedDBAdapter({
dbName: "my-app", // required - database name
storeName: "my-store", // optional - defaults to `${dbName}_store`
encrypt: true, // optional, default false
version: 1, // optional, default 1
expireCheckInterval: 2000, // optional, default 1000ms - 0 turns the timer off
description: "App database", // optional
password: "my-app-secret", // optional - the encryption keys are derived from it (with encrypt)
keyDerivation: "hkdf", // optional, default "hkdf" - "pbkdf2" only for a password the person types
channelName: "idb-channel", // optional - the channel the tabs of the app talk on
enableSyncTabs: true, // optional, default false - tell the other tabs about every write and delete
});
Sync between tabs needs three settings: channelName and enableSyncTabs here, andsyncTabs: true on each store that should follow the other tabs (setInStorage). With only channelName, nothing is told to the other tabs.
2. Core Concepts
Persistent Storage
IndexedDB provides a robust, persistent storage mechanism that can handle significant amounts of structured data. Unlike localStorage or sessionStorage, IndexedDB can store much larger data volumes (typically limited only by disk space) and supports complex data structures.
Database Organization
Data is stored in an object store within the IndexedDB database. Each adapter instance creates or uses a database with the specifieddbName and an object store (default name is{dbName}_store). All keys are automatically namespaced using the format{dbName}__to maintain organization.
Encryption
With encrypt: true every value is encrypted (AES-GCM, a new random IV on every write) and the key names are obfuscated. It makes the values hard to read in the browser's tools; it does not keep a secret — everything needed to decrypt ships with the app (with password, reading also needs the app's secret, which is inside its JavaScript). Never store tokens or passwords.The keys are derived from the password with keyDerivation: "hkdf" (default, fast) or "pbkdf2" (slow on purpose — only for a password the person types). Each value is read the way it was written, values written by 1.2.x included.
Asynchronous Operations
All IndexedDB operations are inherently asynchronous. The adapter handles this complexity internally, providing a clean Promise-based API for all operations that makes asynchronous storage operations straightforward to work with.
Cross-Tab Communication
With channelName and enableSyncTabs: true, every write and delete is told to the other tabs (BroadcastChannel). A store follows them with syncTabs: true; your code can listen with onDataChanged, which returns a function that stops listening.
Expiration Management
The adapter includes a built-in expiration system that automatically removes expired items at regular intervals (configurable viaexpireCheckInterval). This helps manage temporary data without manual cleanup while maintaining long-term data integrity.
Database Versioning
IndexedDB supports versioning to manage schema changes over time. The adapter handles version upgrades automatically when you specify a new version number, ensuring backward compatibility with previously stored data.
3. Test It
wait the animation to finish before go to another tab!
IndexedDB Content:
4. API Reference
await adapter.get(key)
Retrieves a value. Returns null if not found, expired or unreadable — pass { onError } to be told a stored value could not be read (another password, changed by hand). Handles decryption automatically.
await adapter.set("userId", "user123");
const value = await adapter.get("userId"); // "user123"
await adapter.set(key, value, expire?)
Stores a value and answers true (saved), false (failed — e.g. storage full) or null (removed: the value is null, or expire is 0 or less). Optional expire is in milliseconds from now. Writes of a key land in the order they were made. Handles encryption automatically if enabled and broadcasts changes to other tabs if using a channel.
// Save user data that expires in 7 days
await adapter.set("userData", userData, 7 * 24 * 60 * 60 * 1000);
await adapter.delete(key)
Removes a key and its expiration metadata. Also broadcasts deletion to other tabs if using a channel.
await adapter.delete("userId");
await adapter.list(prefix?)
Returns all keys/values matching the prefix (defaults to all in namespace). Decrypts values if encryption is enabled.
await adapter.set("user.name", "John");
await adapter.set("user.email", "john@example.com");
const userData = await adapter.list("user.");
// [{ key: "user.name", value: "John" }, { key: "user.email", value: "john@example.com" }]
await adapter.has(key)
Returns true if the key exists in the IndexedDB store and has not expired.
await adapter.has("userId"); // true or falseawait adapter.clear()
Clears all data, including metadata and expirations, within this adapter's namespace.
await adapter.clear();await adapter.reset()
Removes every data key of the namespace and their expirations, not the metadata — after the writes asked before it (the writes asked after wait for it).
await adapter.reset();await adapter.setExpire(key, timestamp)
Set a custom expiration time (timestamp in ms) for a specific key.
const futureDate = Date.now() + 30 * 24 * 60 * 60 * 1000; // 30 days
await adapter.setExpire("userData", futureDate);
await adapter.getExpire(key)
Returns the expiration timestamp for a key, or null if no expiration is set.
const expireTime = await adapter.getExpire("userData");
// Returns timestamp or null
await adapter.deleteExpire(key)
Removes the expiration for the given key, making it persist indefinitely.
await adapter.deleteExpire("userData");
await adapter.clearExpire()
Deletes all keys that have expired based on their timestamps.
await adapter.clearExpire();
await adapter.waitReadiness(timeout?, tries?)
Waits for the IndexedDB to be ready before proceeding — and rejects with the reason when it does not open (refused, upgraded by another tab, destroyed). The other methods wait by themselves.
await adapter.waitReadiness();
// Now safe to perform operations
adapter.destroy()
Releases the adapter once the writes already asked are done: the expiration timer, the channel between tabs and the database connection. Call it when you stop using the adapter — it is not used after, and it is not called on page unload (a beforeunload listener can keep the page out of the browser's back/forward cache).
await adapter.destroy(); // Clean up before component unmount
adapter.emitDataChange(key, value, origin)
Explicitly broadcasts a data change event to other tabs (usually called automatically by set/delete).
adapter.emitDataChange("appState", newState, "tab-123");
adapter.onDataChanged(callback)
Listens to the changes other tabs tell (needs channelName and enableSyncTabs in the writing tab). The message carries the key and what happened — read the value again withget. Returns a function that stops listening.
const stop = adapter.onDataChanged(async ({ key, origin }) => {
// origin: "set", "delete" or "reset"
const value = await adapter.get(key); // null after a delete
});
stop(); // stops listening
5. Advanced Usage
Offline-First Application Data
The adapter is ideal for managing offline-first application data:
// Store application data for offline use
async function cacheApplicationData(data) {
await adapter.set("app.cache", data);
await adapter.set("app.lastSyncTime", Date.now());
}
// Retrieve cached data when offline
async function getOfflineData() {
return await adapter.get("app.cache");
}
// Check if cache needs refreshing (older than 1 day)
async function shouldRefreshCache() {
const lastSync = await adapter.get("app.lastSyncTime");
if (!lastSync) return true;
const oneDay = 24 * 60 * 60 * 1000;
return (Date.now() - lastSync) > oneDay;
}
User Preferences Management
Managing persistent user preferences:
// Store user preferences
async function saveUserPreferences(preferences) {
await adapter.set("preferences", preferences);
}
// Load user preferences
async function loadUserPreferences() {
return await adapter.get("preferences") || getDefaultPreferences();
}
// Update a single preference
async function updatePreference(key, value) {
const prefs = await loadUserPreferences();
prefs[key] = value;
await saveUserPreferences(prefs);
}
Complex Data Structures with Prefixes
Managing related data using key prefixes:
// Store product data
async function saveProduct(product) {
await adapter.set(`product.${product.id}`, product);
}
// Add product to favorites
async function addToFavorites(productId) {
await adapter.set(`favorite.${productId}`, true);
}
// Get all favorite products
async function getFavoriteProducts() {
const favorites = await adapter.list("favorite.");
const productIds = favorites.map(f => f.key.replace("favorite.", ""));
const products = [];
for (const id of productIds) {
const product = await adapter.get(`product.${id}`);
if (product) products.push(product);
}
return products;
}
Encrypted preferences, grouped by prefix
Encryption keeps the values out of plain sight in the browser's tools — fine for preferences. It does not keep a secret: never store tokens or passwords here.
const preferences = new IndexedDBAdapter({
dbName: "my-app",
encrypt: true,
password: "my-app-secret", // a constant of the app: keyDerivation "hkdf" (the default) is the right one
});
await preferences.set("ui.theme", "dark");
await preferences.set("ui.language", "pt-BR");
// Every key that starts with "ui."
const ui = await preferences.list("ui.");
// [{ key: "ui.theme", value: "dark" }, { key: "ui.language", value: "pt-BR" }]
// Forget them all
for (const { key } of ui) {
await preferences.delete(key);
}
5. Comparison with Other Storage Adapters
| Feature | IndexedDBAdapter | LocalStorageAdapter | SessionStorageAdapter |
|---|---|---|---|
| Persistence | Persistent until explicitly cleared | Persistent until explicitly cleared | Until tab/browser closes |
| Storage Capacity | Large (typically 50MB-unlimited) | ~5MB per origin | ~5MB per origin |
| Performance | Optimized for large datasets | Fast for small data | Fast for small data |
| Complexity | More complex, async API | Simple, synchronous underlying API | Simple, synchronous underlying API |
| Best Use Cases | Large datasets, offline apps, complex data structures | User preferences, app settings | Form state, wizards, the state of one tab |
| Browser Support | All modern browsers | All browsers | All browsers |
| Cross-Tab Sync | Requires explicit channelName | Requires explicit channelName | Requires explicit channelName |
6. Notes
- IndexedDB operations are asynchronous - always use
awaitwhen calling adapter methods. - Every method waits for the database to open by itself;
waitReadiness()is there when you need to know it is open. A write answerstrueonly once its transaction is saved. - The object store is created with the database, or when its
versionis raised. The samedbNameopened with anotherstoreNameat the same version is refused with the reason (writes answerfalse, readsnull, throughonError) — mind the defaults:startStoragefyuses"storagefy_db", the class`${dbName}_store`. When a tab opens a higherversion, the tabs on the older one close it and fail with "upgraded by another tab — reload the page". - Use
encrypt: trueto keep values out of plain sight — it does not protect a secret: never store tokens or passwords. - Keys are namespaced under
{dbName}__to avoid conflicts. - Expirations are automatically checked and cleared at the specified interval (default 1s).
- For very large datasets, consider implementing pagination or lazy loading patterns.
- IndexedDB has excellent support across modern browsers but may require polyfills for older browsers.
- For complex data models, consider using multiple adapters with different store names within the same database.