Overview
StorageManager.js provides a convenient and feature-rich interface to handle
localStorage
and sessionStorage
. It simplifies
common tasks and adds powerful features like automatic item expiration,
batch operations, optional data compression using LZString, and storage
event listeners.
Key Features
-
Switch between
localStorage
andsessionStorage
easily. - Set items to expire automatically after a specified duration.
-
Perform batch
set
,get
, andremove
operations efficiently. - Optionally compress stored data to save space (requires LZString).
- Listen for changes to specific storage keys across tabs/windows.
- Automatically cleans up expired items on initialization.
-
Check for key existence (
has
) without retrieving the value. - List all keys within a defined namespace (
keys
). -
Retrieve all key-value pairs in the namespace (
getAll
). - Unsubscribe from change listeners (
offChange
). - Supports namespacing to avoid key collisions.
Installation
Include the script directly in your HTML, or install via npm for use with build systems.
NPM Installation
npm install web-storage-manager-js
# or
yarn add web-storage-manager-js
// Import in your project
import StorageManager from 'web-storage-manager-js';
Direct Include
<!-- Include directly from CDN (replace x.y.z with the desired version) -->
<script src="https://cdn.jsdelivr.net/npm/web-storage-manager@x.y.z/StorageManager.js"></script>
<!-- Or download and include locally -->
<script src="path/to/StorageManager.js"></script>
<!-- LZString is loaded automatically when compression is enabled -->
Basic Usage
Instantiate StorageManager
, optionally configuring the storage
type, namespace, default expirations, and compression.
// Use localStorage, namespace 'myApp', default 1min expiry for 'sessionInfo'
const localManager = new StorageManager(false, {
namespace: 'myApp',
defaultExpiration: { sessionInfo: 60 }, // 60 seconds
enableCompression: true // Default is true
});
// Use sessionStorage, namespace 'tempData', compression disabled
const sessionManager = new StorageManager(true, {
namespace: 'tempData',
enableCompression: false
});
// --- Basic Operations ---
// Set a value (automatically stringified, compressed if enabled)
await localManager.set('userProfile', { name: 'Alice', theme: 'dark' });
// Get a value (automatically decompressed if needed, parsed)
const profile = await localManager.get('userProfile');
console.log(profile); // Output: { name: 'Alice', theme: 'dark' }
// Set an item with a specific expiration (e.g., 5 minutes)
await localManager.set('tempToken', 'xyz123');
await localManager.expires('tempToken', 300); // 300 seconds
// Check if a key exists and is not expired
const hasToken = await localManager.has('tempToken');
console.log('Has token?', hasToken);
// Remove an item
await localManager.remove('tempToken');
// Get all keys in the namespace
const appKeys = await localManager.keys();
console.log(appKeys); // Output: ['userProfile'] (if tempToken was removed)
// Listen for changes to a key (e.g., from another tab)
localManager.onChange('userProfile', (newValue, oldValue) => {
console.log('User profile changed:', newValue);
});
// Stop listening
localManager.offChange('userProfile');
// Clear all items in the namespace (use with caution!)
// await localManager.clear();
API Reference
All methods that interact with storage (like `set`, `get`, `expires`, etc.) are `async` when compression is enabled, due to the potential loading of LZString. They return Promises.
new StorageManager(useSession?, options?)
Creates a new StorageManager instance.
-
useSession
(Boolean, optional): Iftrue
, usessessionStorage
. Defaults tofalse
(useslocalStorage
). -
options
(Object, optional): Configuration options:-
namespace
(String): Prepends this string and a colon (:
) to all keys. Default:""
. -
defaultExpiration
(Object): Map of key names to default expiration times in seconds. Example:{ userToken: 3600 }
. Default:{}
. -
enableCompression
(Boolean): Whether to use LZString compression. Requires LZString library (loaded automatically via CDN if needed). Default:true
.
-
async set(key, value)
Stores a JSON-serializable value
associated with the
key
. Throws an error if value
is not valid JSON.
Applies compression if enabled. Triggers default expiration if configured.
async get(key)
Retrieves the value associated with key
. Returns the parsed
value, or null
if the key doesn't exist or the item has expired
(and removes the expired item).
async expires(key, expiresIn)
Sets or updates the expiration time for an existing key
.
expiresIn
is the time in seconds from now.
async remove(key)
Removes the item associated with key
and clears any expiration
timer.
async has(key)
Checks if a key
exists in storage and has not expired. Returns
true
or false
.
async keys()
Returns an array of all keys within the instance's namespace that are currently in storage (does not check expiration).
async getAll()
Retrieves all non-expired key-value pairs within the instance's namespace. Returns an object mapping keys to their values.
async batchSet(items)
Stores multiple items efficiently. items
is an array of
objects, each with key
, value
, and optional
expiresIn
properties. Example:
[{ key: 'a', value: 1 }, { key: 'b', value: 2, expiresIn: 60 }]
.
async batchGet(keys)
Retrieves multiple items. keys
is an array of key names.
Returns an object mapping requested keys to their values (or
null
if not found/expired).
async batchRemove(keys)
Removes multiple items specified in the keys
array.
async clear()
Removes all items associated with the instance's namespace from storage. Use with caution!
onChange(key, callback)
Registers a callback
function to be executed when the value
associated with key
changes in storage (typically triggered by
actions in other tabs/windows via the native 'storage' event). The callback
receives (newValue, oldValue)
.
offChange(key)
Unregisters the change listener for the specified key
.
cleanup()
Manually triggers a cleanup of expired items within the namespace. This is also called automatically during instantiation.
Live Demo
Interact with a StorageManager
instance to see its
capabilities. Configure options below.
Configuration
Prefix for all keys to prevent collisions
JSON object mapping keys to expiration seconds
Storage Operations
The key to use for storage operations.
Set expiration when using 'Set' or 'Expires'.
Enter a valid JSON value for the 'Set' operation.
Basic Operations
Advanced Operations
Batch Operations
Will create several keys with different values and expirations, then retrieve them.
Demo output will appear here...
Current Storage State (localStorage, Namespace: demo)
Loading storage state...