Web Development · Module 6 · Lesson 41 min read

Local Storage

Saving data in the browser

localStorage keeps small amounts of data on the user's device, even after the browser is closed.

JavaScript
localStorage.setItem("theme", "dark");
localStorage.getItem("theme");     // "dark"
localStorage.removeItem("theme");
localStorage.clear();

It only stores strings

Use JSON for objects and arrays:

JavaScript
localStorage.setItem("todos", JSON.stringify(todos));
const todos = JSON.parse(localStorage.getItem("todos")) ?? [];

Storage options compared

localStoragesessionStorageCookiesIndexedDB
Lifetimeuntil cleareduntil the tab closesuntil expiryuntil cleared
Size~5 MB~5 MB~4 KBlarge
Sent to the servernonoyes, every requestno
Good forsettings, draftsper-tab statesessionsoffline 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

HTML
<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>