Skip to content

Advanced Features

These examples showcase advanced features like expiration, batch operations, compression, and cross-tab synchronization.

Store temporary data that expires after a set duration.

const storage = new StorageManager(false, {
namespace: 'tempData',
defaultExpiration: {
session: 60, // Sessions expire in 60 seconds
},
enableCompression: false
});
// Store a temporary session
async function createSession() {
await storage.set('session', {
token: 'abc123',
user: 'Alice',
timestamp: Date.now()
});
console.log('Session created, expires in 60 seconds');
checkSession();
}
// Check if session is still valid
async function checkSession() {
const hasSession = await storage.has('session');
const session = await storage.get('session');
document.getElementById('status').textContent =
hasSession ? `Active: ${session.user}` : 'Expired';
}
// Check every second
setInterval(checkSession, 1000);

Efficiently handle multiple items at once.

const storage = new StorageManager(false, {
namespace: 'batchDemo',
enableCompression: false
});
// Initialize with batch set
async function initialize() {
await storage.batchSet([
{ key: 'user1', value: { name: 'Alice', role: 'admin' } },
{ key: 'user2', value: { name: 'Bob', role: 'user' } },
{ key: 'user3', value: { name: 'Charlie', role: 'user' } },
{ key: 'settings', value: { theme: 'dark', lang: 'en' } }
]);
console.log('Batch set complete');
displayData();
}
// Retrieve multiple items
async function displayData() {
const data = await storage.batchGet([
'user1', 'user2', 'user3', 'settings'
]);
const output = document.getElementById('output');
output.innerHTML = Object.entries(data)
.map(([key, value]) =>
`<div><strong>${key}:</strong> ${JSON.stringify(value, null, 2)}</div>`
)
.join('');
}
// Remove multiple items
async function cleanup() {
await storage.batchRemove(['user1', 'user2', 'user3']);
console.log('Users removed');
displayData();
}

A complete shopping cart that expires after 30 minutes of inactivity.

const storage = new StorageManager(false, {
namespace: 'shop',
defaultExpiration: {
cart: 1800 // 30 minutes
},
enableCompression: true
});
// Add item to cart
async function addToCart(item) {
let cart = await storage.get('cart') || [];
const existing = cart.find(i => i.id === item.id);
if (existing) {
existing.quantity++;
} else {
cart.push({ ...item, quantity: 1 });
}
await storage.set('cart', cart);
displayCart();
}
// Display cart
async function displayCart() {
const cart = await storage.get('cart') || [];
const cartEl = document.getElementById('cart');
if (cart.length === 0) {
cartEl.innerHTML = '<p>Cart is empty</p>';
return;
}
const total = cart.reduce((sum, item) =>
sum + (item.price * item.quantity), 0
);
cartEl.innerHTML = cart.map(item =>
\`<div>\${item.name} x\${item.quantity} - $\${(item.price * item.quantity).toFixed(2)}</div>\`
).join('') + \`<div><strong>Total: $\${total.toFixed(2)}</strong></div>\`;
}
// Sample products
const products = [
{ id: 1, name: 'Widget', price: 9.99 },
{ id: 2, name: 'Gadget', price: 19.99 },
{ id: 3, name: 'Doohickey', price: 14.99 }
];

Open this example in multiple tabs to see real-time synchronization.

const storage = new StorageManager(false, {
namespace: 'multiTab',
enableCompression: false
});
// Initialize
let currentUser = await storage.get('currentUser') || null;
updateDisplay();
// Listen for changes from other tabs
storage.onChange('currentUser', (newUser) => {
currentUser = newUser;
updateDisplay();
showNotification('User updated in another tab!');
});
// Login
async function login(username) {
currentUser = { username, loginTime: new Date().toISOString() };
await storage.set('currentUser', currentUser);
updateDisplay();
}
// Logout
async function logout() {
currentUser = null;
await storage.remove('currentUser');
updateDisplay();
}
function updateDisplay() {
const display = document.getElementById('userDisplay');
if (currentUser) {
display.innerHTML = \`Logged in as: <strong>\${currentUser.username}</strong>\`;
} else {
display.innerHTML = 'Not logged in';
}
}

When building advanced applications with StorageManager.js:

  1. Use namespaces to avoid key collisions between features
  2. Set appropriate expirations for temporary data
  3. Use batch operations when working with multiple items
  4. Enable compression for large objects to save space
  5. Clean up listeners when components unmount
  6. Validate data retrieved from storage before using it
  7. Handle null values gracefully (expired or missing keys)

You’ve now seen the full power of StorageManager.js! For detailed API documentation, visit the API Reference.