Remembering things
Your theme choice, a draft message, whether you're signed in — browsers have several places to keep data, each with different lifetimes and rules. Choosing the right one matters for both convenience and security.
The options
- localStorage — strings by key, kept until cleared. Per site. Good for preferences and drafts. Readable by any script on the page, so never store secrets there.
- sessionStorage — like localStorage, but only for this tab, gone when it closes.
- Cookies — small values sent to the server with every request. Sign-in sessions use cookies marked HttpOnly (JavaScript can't read them), Secure (HTTPS only) and SameSite (limits cross-site sending).
- IndexedDB — a real database in the browser for large or structured data (offline apps).
function loadSettings() {
try {
const raw = localStorage.getItem("settings:v1");
return { theme: "light", ...(raw ? JSON.parse(raw) : {}) };
} catch {
return { theme: "light" };
}
}
function saveSettings(s) {
try {
localStorage.setItem("settings:v1", JSON.stringify(s));
} catch {
// Storage full or blocked (e.g. private mode): carry on without saving.
}
}
saveSettings({ theme: "dark" });
console.log(loadSettings());