Quick Start
This guide will walk you through the basics of using StorageManager.js. By the end, you’ll be able to store, retrieve, and manage data in browser storage with ease.
Creating an Instance
Section titled “Creating an Instance”First, create a new StorageManager instance. You can configure it to use either localStorage or sessionStorage, and customize options like namespace, default expiration, and compression.
// Use localStorage (default) with compression enabledconst storage = new StorageManager(false, { namespace: 'myApp', enableCompression: true // Default is true});
// Use sessionStorage with compression disabledconst sessionStorage = new StorageManager(true, { namespace: 'tempData', enableCompression: false});Basic Operations
Section titled “Basic Operations”Storing Data
Section titled “Storing Data”Store any JSON-serializable value using the set() method:
// Store a simple valueawait storage.set('username', 'Alice');
// Store an objectawait storage.set('userProfile', { name: 'Alice', email: 'alice@example.com', theme: 'dark'});
// Store an arrayawait storage.set('favorites', ['apple', 'banana', 'cherry']);Retrieving Data
Section titled “Retrieving Data”Retrieve stored data using the get() method:
const username = await storage.get('username');console.log(username); // Output: 'Alice'
const profile = await storage.get('userProfile');console.log(profile.theme); // Output: 'dark'If the key doesn’t exist or has expired, get() returns null:
const missing = await storage.get('nonexistent');console.log(missing); // Output: nullRemoving Data
Section titled “Removing Data”Remove a stored item using the remove() method:
await storage.remove('username');Checking for Existence
Section titled “Checking for Existence”Check if a key exists (and is not expired) without retrieving its value:
const hasProfile = await storage.has('userProfile');console.log(hasProfile); // Output: true or falseSetting Expiration
Section titled “Setting Expiration”One of the most powerful features of StorageManager.js is automatic expiration. Set an expiration time (in seconds) for any item:
// Store a temporary tokenawait storage.set('authToken', 'abc123');
// Set it to expire in 5 minutes (300 seconds)await storage.expires('authToken', 300);You can also set a default expiration for specific keys when creating the instance:
const storage = new StorageManager(false, { namespace: 'myApp', defaultExpiration: { authToken: 300, // 5 minutes sessionInfo: 3600 // 1 hour }});
// Now authToken will automatically expire in 5 minutes when setawait storage.set('authToken', 'abc123');Listing Keys
Section titled “Listing Keys”Get an array of all keys within your namespace:
const allKeys = await storage.keys();console.log(allKeys); // Output: ['userProfile', 'favorites', ...]Getting All Data
Section titled “Getting All Data”Retrieve all non-expired key-value pairs in your namespace:
const allData = await storage.getAll();console.log(allData);// Output: { userProfile: {...}, favorites: [...], ... }Listening for Changes
Section titled “Listening for Changes”Listen for changes to a specific key across tabs or windows:
// In tab/window 1: Register a listenerstorage.onChange('userProfile', (newValue, oldValue) => { console.log('User profile changed!'); console.log('Old:', oldValue); console.log('New:', newValue);});
// In tab/window 2: Change the valueawait storage.set('userProfile', { name: 'Bob', theme: 'light' });
// Tab/window 1 will receive the change notificationTo stop listening, use offChange():
storage.offChange('userProfile');Clearing All Data
Section titled “Clearing All Data”To remove all items in your namespace:
await storage.clear();Complete Example
Section titled “Complete Example”Here’s a complete example putting it all together:
// Create a storage manager for user dataconst userStorage = new StorageManager(false, { namespace: 'myApp', defaultExpiration: { session: 3600 }, // 1 hour enableCompression: true});
// Store user profileawait userStorage.set('profile', { name: 'Alice', email: 'alice@example.com', preferences: { theme: 'dark', notifications: true }});
// Store session data with automatic expirationawait userStorage.set('session', { token: 'xyz789', loginTime: Date.now() });
// Retrieve and use the dataconst profile = await userStorage.get('profile');console.log(`Welcome back, ${profile.name}!`);
// Check if session is still validconst hasSession = await userStorage.has('session');if (hasSession) { console.log('User is authenticated');} else { console.log('Session expired, please login again');}
// Listen for profile changes from other tabsuserStorage.onChange('profile', (newProfile) => { console.log('Profile updated:', newProfile);});
// Later: Clean upawait userStorage.remove('session');Next Steps
Section titled “Next Steps”Now that you know the basics, explore the API Reference to learn about all available methods and advanced features like batch operations.