LocalStorage Wrapper with Expiry

JavaScript Beginner 👁️ 872 views By system Added Just now

Enhanced localStorage with TTL (time to live) and type safety

0
JavaScript Code
const storage = {
    set: function(key, value, ttl = null) {
        const item = {
            value: value,
            expiry: ttl ? Date.now() + ttl : null
        };
        localStorage.setItem(key, JSON.stringify(item));
    },
    
    get: function(key) {
        const itemStr = localStorage.getItem(key);
        if (!itemStr) return null;
        
        try {
            const item = JSON.parse(itemStr);
            
            // Check if expired
            if (item.expiry && Date.now() > item.expiry) {
                localStorage.removeItem(key);
                return null;
            }
            
            return item.value;
        } catch(e) {
            return null;
        }
    },
    
    remove: function(key) {
        localStorage.removeItem(key);
    },
    
    clear: function() {
        localStorage.clear();
    },
    
    // Get all keys with optional prefix filter
    keys: function(prefix = "") {
        const keys = [];
        for(let i = 0; i < localStorage.length; i++) {
            const key = localStorage.key(i);
            if(key.startsWith(prefix)) {
                keys.push(key);
            }
        }
        return keys;
    },
    
    // Get storage usage in bytes
    size: function() {
        let total = 0;
        for(let i = 0; i < localStorage.length; i++) {
            const key = localStorage.key(i);
            const value = localStorage.getItem(key);
            total += key.length + value.length;
        }
        return total;
    }
};

// Usage
storage.set("user", {name: "John", age: 30}, 3600000); // Expires in 1 hour
storage.set("theme", "dark");

const user = storage.get("user"); // Returns object or null if expired
console.log(user);

// Session storage wrapper (same API but with sessionStorage)
const session = {...storage};
session.set = function(key, value, ttl = null) {
    const item = {
        value: value,
        expiry: ttl ? Date.now() + ttl : null
    };
    sessionStorage.setItem(key, JSON.stringify(item));
};
session.get = function(key) {
    const itemStr = sessionStorage.getItem(key);
    if (!itemStr) return null;
    try {
        const item = JSON.parse(itemStr);
        if (item.expiry && Date.now() > item.expiry) {
            sessionStorage.removeItem(key);
            return null;
        }
        return item.value;
    } catch(e) {
        return null;
    }
};

Explanation

This wrapper enhances localStorage with expiration times and type safety. It automatically handles JSON serialization, checks for expired items, and provides utility methods for key management and storage size calculation. Perfect for caching API responses or storing user preferences with TTL.