Session Storage Adapter
The SessionStorageAdapter extends the abstract StorageAdapter class, providing a concrete implementation for persisting data to browser'ssessionStorage. Unlike LocalStorageAdapter, data stored with this adapter is cleared when the browser session ends. 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 { SessionStorageAdapter } from "storagefy";
const adapter = new SessionStorageAdapter({
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: "Session 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: "session-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
Session-Based Storage
Unlike localStorage, data in sessionStorage is cleared when the page session ends — that is, when the tab is closed or the browser is shut down. This makes it ideal for temporary data that should not persist beyond the current browser session.
Storage Namespacing
All keys are automatically namespaced using the format {dbName}__ to avoid conflicts with other applications using sessionStorage. 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!
SessionStorage 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("sessionId", "abc123");
const value = await adapter.get("sessionId"); // "abc123"
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 a form state that expires in 30 minutes
await adapter.set("formState", formData, 30 * 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("sessionId");
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("form.name", "John");
await adapter.set("form.email", "john@example.com");
const formData = await adapter.list("form.");
// [{ key: "form.name", value: "John" }, { key: "form.email", value: "john@example.com" }]
await adapter.has(key)
Returns true if the key exists in the session storage and has not expired.
await adapter.has("sessionId"); // 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("sessionId", future);
await adapter.getExpire(key)
Returns the expiration timestamp for a key, or null if no expiration is set.
const expireTime = await adapter.getExpire("sessionId");
// Returns timestamp or null
await adapter.deleteExpire(key)
Removes the expiration for the given key, making it persist until the session ends.
await adapter.deleteExpire("sessionId");
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 component unmount
adapter.emitDataChange(key, value, origin)
Explicitly broadcasts a data change event to other tabs (usually called automatically by set/delete).
adapter.emitDataChange("wizard-state", 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
Multi-Step Form Data Management
The adapter is ideal for managing state in multi-step forms where you want to preserve progress within a session:
// Save form state after each step
function saveFormStep(stepNumber, formData) {
adapter.set(`form-step-${stepNumber}`, formData);
}
// Recover a specific step's data
async function loadFormStep(stepNumber) {
return await adapter.get(`form-step-${stepNumber}`);
}
// Check if a step has been completed
async function isStepCompleted(stepNumber) {
return await adapter.has(`form-step-${stepNumber}`);
}
A form draft that expires
Keep what the person typed for 20 minutes — gone when the tab closes:
const DRAFT_LIFETIME = 20 * 60 * 1000; // ms from now
await adapter.set("contact-draft", { subject, message }, DRAFT_LIFETIME);
// Push the end forward while the person types
async function keepDraft(draft) {
await adapter.set("contact-draft", draft, DRAFT_LIFETIME);
}
// null once it expired
const draft = await adapter.get("contact-draft");
Multi-Tab Wizard Synchronization
Keep multi-step wizards in sync across tabs:
// In your wizard component
const wizardAdapter = new SessionStorageAdapter({
dbName: "wizard",
channelName: "wizard-sync"
});
// Update current step
function goToStep(stepNumber) {
wizardAdapter.set("current-step", stepNumber);
}
// Listen for changes from other tabs
wizardAdapter.onDataChanged(({ key, value }) => {
if (key === "current-step") {
// Update the UI to show the new step
renderWizardStep(value);
}
});
6. Comparison with LocalStorageAdapter
| Feature | SessionStorageAdapter | LocalStorageAdapter |
|---|---|---|
| Persistence | Until tab/browser closes | Indefinite (until manually cleared) |
| Data Visibility | Only within the same tab by default | Available across all tabs/windows |
| Best Use Cases | Form state, wizards, the state of one tab | User preferences, long-term settings, cached data |
| Storage Limit | ~5MB per origin | ~5MB per origin |
| Cross-Tab Sync | Requires explicit channelName | Requires explicit channelName |
7. Notes
- Data is automatically cleared when the browser session ends (tab closed, browser shut down).
- 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. - The adapter handles browser storage limits gracefully with error logging.
- Use
channelNameif you need to synchronize session data across multiple tabs.