Local Storage Adapter
The LocalStorageAdapter extends the abstract StorageAdapter class, providing a concrete implementation for persisting data to browser'slocalStorage. It offers enhanced capabilities including encryption, expiration management, metadata tracking, and optional cross-tab synchronization.
1. Getting Started
Initialize the adapter with the desired options:
import { LocalStorageAdapter } from "storagefy";
const adapter = new LocalStorageAdapter({
dbName: "my-app", // required - creates namespace for your keys
encrypt: true, // optional, default false
version: 1, // optional, default 1
expireCheckInterval: 2000, // optional, default 1000ms - 0 turns the timer off
description: "Main app store", // 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: "main-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
Storage Namespacing
All keys are automatically namespaced using the format {dbName}__ to avoid conflicts with other applications using localStorage. When encryption is enabled, keys are additionally obfuscated using a simple algorithm.
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.
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 via expireCheckInterval). This helps manage temporary data without manual cleanup.
3. Test It
wait the animation to finish before go to another tab!
LocalStorage 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("theme", "dark");
const value = await adapter.get("theme"); // "dark"
await adapter.set(key, value, expire?)
Stores a value and answers true (saved), false (failed — e.g. storage full) ornull (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 a theme that expires in 5 seconds
await adapter.set("theme", "dark", 5000);
await adapter.delete(key)
Removes a key and its expiration metadata. Also broadcasts deletion to other tabs if using a channel.
await adapter.delete("theme");
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("a", 1);
await adapter.set("b", 2);
const list = await adapter.list();
// [{ key: "a", value: 1 }, { key: "b", value: 2 }]
await adapter.has(key)
Returns true if the key exists and has not expired.
await adapter.has("a"); // true or false
await 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 future = Date.now() + 10000;
await adapter.setExpire("countries", future);
await adapter.getExpire(key)
Returns the expiration timestamp for a key, or null if no expiration is set.
const expireTime = await adapter.getExpire("countries");
// Returns timestamp or null
await adapter.deleteExpire(key)
Removes the expiration for the given key, making it permanent.
await adapter.deleteExpire("countries");
await adapter.clearExpire()
Deletes all keys that have expired based on their timestamps.
await adapter.clearExpire();
adapter.destroy()
Releases the adapter once the writes already asked are done: the expiration timer, the channel between tabs. 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 unmounting
adapter.emitDataChange(key, value, origin)
Explicitly broadcasts a data change event to other tabs (usually called automatically by set/delete).
adapter.emitDataChange("settings", newSettings, "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
State Management Integration
The adapter can be used to persist and synchronize state management libraries like Vuex, Pinia, Redux, or Zustand across tabs:
// With Pinia store
const userStore = useUserStore();
// Listen for external changes
adapter.onDataChanged(async ({ key }) => {
if (key === "user-data") {
// The message carries the key: read the value again
userStore.updateUser(await adapter.get(key));
}
});
// Save changes from this tab
watch(() => userStore.user, (newValue) => {
adapter.set("user-data", newValue);
});
A cache that expires
Keep an answer of your API for an hour — expire is a duration, in ms from now:
const ONE_HOUR = 60 * 60 * 1000;
await adapter.set("countries", countries, ONE_HOUR);
// null once it expired: fetch it again
const cached = await adapter.get("countries");
6. Notes
- Keys are namespaced under
{dbName}__to avoid conflicts. - Expirations are automatically checked and removed in intervals (default 1s).
- Encryption only applies with
encrypt: true, and only makes reading harder — never store tokens or passwords. - Use
channelNameto sync updates across tabs (e.g. for state management libraries). - The adapter handles browser storage limits gracefully with error logging.
- Destroyed adapters should be re-initialized if needed again.