Browser-side preferences often need to survive a reload without being sent back to the server on every request. localStorage gives JavaScript a same-origin storage area for small string values such as a theme choice, layout density, or a dismissed banner state.
The Storage methods keep the code explicit: setItem() writes a key, getItem() returns a string or null, and removeItem() deletes one key. A stable application prefix, such as sg:theme, avoids collisions with unrelated values from the same origin.
Use localStorage only for non-sensitive client state that the application can recreate. Browser privacy settings, private sessions, storage quotas, and direct file: URLs can change whether storage is available or how long values remain, so server-side authorization, secrets, and required data belong somewhere else.
const storageKey = "sg:theme"; const fallbackTheme = "light"; const themeSelect = document.querySelector("#theme"); const status = document.querySelector("#theme-status"); function applyTheme(theme) { document.documentElement.dataset.theme = theme; themeSelect.value = theme; status.textContent = `localStorage ${storageKey}=${theme}`; }
localStorage is scoped by origin, including scheme, host, and port. A page on https://example.com does not share the same storage object as http://example.com.
const savedTheme = localStorage.getItem(storageKey) ?? fallbackTheme; applyTheme(savedTheme);
getItem() returns null when the key does not exist. The nullish coalescing operator keeps the fallback only for missing values.
themeSelect.addEventListener("change", (event) => { const selectedTheme = event.target.value; localStorage.setItem(storageKey, selectedTheme); applyTheme(selectedTheme); });
Do not store passwords, access tokens, personal records, or authorization state in localStorage. Any script running on the same origin can read the stored value.
const resetButton = document.querySelector("#reset-theme"); resetButton.addEventListener("click", () => { localStorage.removeItem(storageKey); applyTheme(fallbackTheme); });
> localStorage.getItem("sg:theme")
"dark"
> localStorage.getItem("sg:theme")
"dark"
> localStorage.getItem("sg:theme")
"dark"
> localStorage.getItem("sg:theme")
null