Back to Snippets
CODE
Local Storage with Expiry
Description
Enhanced localStorage with automatic expiry, supports TTL (Time-To-Live) for stored items
Code
/**
* LocalStorage with expiry support
*/
const ExpiryStorage = {
/**
* Set item with expiry
* @param key Storage key
* @param value Value to store
* @param ttl Time-to-live in milliseconds (default: 24h)
*/
setItem<T>(key: string, value: T, ttl = 86400000): void {
const item = {
value,
expiry: Date.now() + ttl
};
localStorage.setItem(key, JSON.stringify(item));
},
/**
* Get item (returns null if expired)
* @param key Storage key
* @returns Stored value or null
*/
getItem<T>(key: string): T | null {
const itemStr = localStorage.getItem(key);
if (!itemStr) return null;
const item = JSON.parse(itemStr);
if (Date.now() > item.expiry) {
localStorage.removeItem(key);
return null;
}
return item.value as T;
},
/**
* Remove item
* @param key Storage key
*/
removeItem(key: string): void {
localStorage.removeItem(key);
},
/**
* Clear all items
*/
clear(): void {
localStorage.clear();
}
};
// Usage Example
ExpiryStorage.setItem('user', { id: 1, name: 'John' }, 3600000); // 1 hour TTL
const user = ExpiryStorage.getItem('user'); // { id: 1, name: 'John' } (if not expired)Usage
Perfect for caching API responses, user sessions, or temporary data with automatic cleanup