Storage Patterns
Build a reusable storage service with typed getters/setters, versioning, and automatic JSON serialization to avoid repeating boilerplate code.
Build a reusable storage service with typed getters/setters, versioning, and automatic JSON serialization to avoid repeating boilerplate code.
// Typed storage service
class StorageService {
constructor(prefix = "app") {
this.prefix = prefix;
}
key(name) { return `${this.prefix}:${name}`; }
set(name, value) {
localStorage.setItem(this.key(name), JSON.stringify(value));
}
get(name, fallback = null) {
try {
const v = localStorage.getItem(this.key(name));
return v !== null ? JSON.parse(v) : fallback;
} catch { return fallback; }
}
remove(name) { localStorage.removeItem(this.key(name)); }
}
const store = new StorageService("myapp");
store.set("theme", "dark");
store.get("theme", "light"); // "dark"
Namespace storage keys with a prefix (app:key) to avoid collisions with libraries and third-party scripts.
More in JavaScript