Persist small browser preferences deliberately
localStorage and sessionStorage store string key/value pairs for a site origin. localStorage commonly persists beyond a tab session; sessionStorage is scoped to an origin within a top-level browsing context and normally lasts for that tab's session. Neither is a substitute for a server account database.
const key = 'onlinecbt.practice.theme.v1';
function saveTheme(theme) {
if (!['light', 'dark', 'system'].includes(theme)) return false;
try {
localStorage.setItem(key, theme);
return true;
} catch {
return false;
}
}
function loadTheme() {
try {
const value = localStorage.getItem(key);
return ['light', 'dark', 'system'].includes(value) ? value : 'system';
} catch {
return 'system';
}
}
console.log(saveTheme('dark'));
console.log(loadTheme());In an ordinary permitted context, saveTheme returns true and loadTheme returns dark. Browser settings, private modes, policies or quota limits can make storage unavailable; the example retains a safe fallback.
Strings and structured data
setItem converts values to strings. To store a small object, serialize it with JSON.stringify and parse it with error handling. Validate the parsed shape and version before using it. A previous application version or manual browser edit can leave unexpected data.
Security and privacy
Scripts running on the origin can access Web Storage. Do not store passwords, private API keys or sensitive account data there. XSS can expose browser-readable tokens; choose authentication storage according to the application's security design rather than treating localStorage as a secure vault.
Scope and cleanup
Scheme, host and port are part of origin. An HTTP development site and its HTTPS production site do not share storage automatically. removeItem deletes one key; clear removes all keys in that storage area and may disrupt unrelated features. Use namespaced keys and targeted removal.
Practice
- Save a harmless preferred language and restore it on reload.
- Compare localStorage and sessionStorage across reloads and separate tabs.
- Simulate malformed JSON and keep the UI usable.
- Explain why changing a local role string must never grant server admin access.