Local Storage
Saving data in the browser
localStorage keeps small amounts of data on the user's device, even after the browser is closed.
localStorage.setItem("theme", "dark");
localStorage.getItem("theme"); // "dark"
localStorage.removeItem("theme");
localStorage.clear();
It only stores strings
Use JSON for objects and arrays:
localStorage.setItem("todos", JSON.stringify(todos));
const todos = JSON.parse(localStorage.getItem("todos")) ?? [];
Storage options compared
| localStorage | sessionStorage | Cookies | IndexedDB | |
|---|---|---|---|---|
| Lifetime | until cleared | until the tab closes | until expiry | until cleared |
| Size | ~5 MB | ~5 MB | ~4 KB | large |
| Sent to the server | no | no | yes, every request | no |
| Good for | settings, drafts | per-tab state | sessions | offline data, files |
⚠️ Security
- Never store passwords, card numbers or secret tokens in localStorage: any script on the page (including injected XSS) can read it.
- For login sessions, prefer HttpOnly cookies, which JavaScript can't read.
Typical uses: theme choice, unsent form drafts, a small to-do list, "don't show again" flags.
Example
<button id="theme">Toggle dark mode</button>
<p>Visits on this device: <span id="count"></span></p>
<style>
body.dark { background: #0f172a; color: #e2e8f0; }
</style>
<script>
// Remember the theme
if (localStorage.getItem("theme") === "dark") document.body.classList.add("dark");
document.querySelector("#theme").addEventListener("click", () => {
const dark = document.body.classList.toggle("dark");
localStorage.setItem("theme", dark ? "dark" : "light");
});
// Count visits (numbers are stored as text)
const visits = Number(localStorage.getItem("visits") ?? 0) + 1;
localStorage.setItem("visits", String(visits));
document.querySelector("#count").textContent = visits;
</script>