Storage Best Practices
Follow these guidelines for robust and secure storage: namespace keys, version schemas, serialize safely, handle quota errors, and avoid storing sensitive data.
Follow these guidelines for robust and secure storage: namespace keys, version schemas, serialize safely, handle quota errors, and avoid storing sensitive data.
// 1. Namespace keys to avoid conflicts
localStorage.setItem("myapp:theme", "dark");
// 2. Always use try/catch around parse
function safeGet(key) {
try { return JSON.parse(localStorage.getItem(key)); }
catch { return null; }
}
// 3. Handle QuotaExceededError
function safeSet(key, val) {
try { localStorage.setItem(key, JSON.stringify(val)); }
catch (e) { if (e.name === "QuotaExceededError") handleFull(); }
}
// 4. Clean up expired data
const cached = safeGet("cache");
if (cached && cached.expiresAt < Date.now()) {
localStorage.removeItem("cache");
}
Store an expiresAt timestamp alongside cached data so you can invalidate it on the next read.
More in JavaScript