Tutorials / Modern JavaScript: Async, Modules and the Browser / Local storage and session storage

Local storage and session storage

13 min read javascript
Course contents (16 lessons)
  1. Modern syntax
  2. Destructuring, spread and rest
  3. ES modules: import and export
  4. Objects, this and errors
  5. Classes and prototypes
  6. Understanding this in JavaScript
  7. Error handling: try, catch and custom errors
  8. Asynchronous JavaScript
  9. The event loop: how JavaScript handles waiting
  10. From callbacks to promises to async/await
  11. Fetch and REST APIs
  12. Working in the browser
  13. Local storage and session storage
  14. Debugging with browser DevTools
  15. Performance basics: debounce and throttle
  16. Node.js essentials
  17. Node.js and npm basics
  18. Working with files in Node.js
  19. A tiny HTTP server with Node.js
  20. Testing and the final project
  21. Testing basics with the Node.js test runner
  22. Final project: a post explorer with modules and fetch

Remembering things

Variables disappear when the page reloads. For small bits of data that should survive, such as a theme choice, a draft or a to-do list, the browser gives you the Web Storage API. It has two parts with the same methods.

  • localStorage keeps data until the user or your code clears it. It survives closing the browser.
  • sessionStorage keeps data for one tab. It is cleared when the tab closes.

Data is stored per origin, that is, per combination of protocol, domain and port. https://example.com cannot read what https://other.com stored.

The basic methods

localStorage.setItem("theme", "dark");

const theme = localStorage.getItem("theme");
console.log(theme); // "dark"

console.log(localStorage.getItem("missing")); // null

localStorage.removeItem("theme");
localStorage.clear();            // remove everything for this origin
console.log(localStorage.length);

Keys and values are both strings. getItem returns null when the key does not exist. If you store a number, you get a string back:

localStorage.setItem("visits", 5);
console.log(localStorage.getItem("visits"));        // "5"
console.log(typeof localStorage.getItem("visits")); // "string"

Storing objects and arrays

Convert them to JSON text on the way in, and parse on the way out:

const settings = { theme: "dark", fontSize: 18, tags: ["js", "web"] };
localStorage.setItem("settings", JSON.stringify(settings));

const loaded = JSON.parse(localStorage.getItem("settings"));
console.log(loaded.tags[0]); // "js"

If you try localStorage.setItem("settings", settings) without stringify, JavaScript stores "[object Object]", which is useless. This mistake is very common.

A safe wrapper

Reading storage can fail. The value might not exist, the text might be damaged, or the browser might block storage in private mode. A small wrapper makes everything simpler:

const storage = {
  get(key, fallback = null) {
    try {
      const raw = localStorage.getItem(key);
      return raw === null ? fallback : JSON.parse(raw);
    } catch {
      return fallback;
    }
  },
  set(key, value) {
    try {
      localStorage.setItem(key, JSON.stringify(value));
      return true;
    } catch {
      return false;   // storage full or blocked
    }
  },
  remove(key) {
    try { localStorage.removeItem(key); } catch {}
  },
};

storage.set("favourites", [3, 7, 12]);
console.log(storage.get("favourites", []));   // [3, 7, 12]
console.log(storage.get("unknown", []));      // []

The code that uses the wrapper never has to think about null, JSON.parse errors, or exceptions. I put this in a storage.js module in most small projects.

Example: remember a theme

const button = document.querySelector("#theme-toggle");

function applyTheme(theme) {
  document.body.dataset.theme = theme;
  storage.set("theme", theme);
}

applyTheme(storage.get("theme", "light"));

button.addEventListener("click", () => {
  const next = document.body.dataset.theme === "dark" ? "light" : "dark";
  applyTheme(next);
});

On load we apply the saved theme or "light". Each click flips it and saves it. In the CSS, you can style [data-theme="dark"].

Listening for changes in other tabs

When another tab of the same site changes localStorage, your tab gets a storage event:

window.addEventListener("storage", event => {
  if (event.key === "theme") applyTheme(event.newValue.replace(/"/g, ""));
});

It does not fire in the tab that made the change. It is useful for keeping a logged-in state in sync across tabs.

Limits you should know

  • About 5 MB per origin, depending on the browser. Do not store large data.
  • Everything is synchronous. Writing a lot of data blocks the page.
  • Only strings. Binary data needs encoding.
  • Data can be cleared by the user at any time. Never treat it as permanent.
  • For larger or structured data, look at IndexedDB. For files, the Cache API or the File System Access API.

Security: do not store secrets

Any script running on your page can read localStorage. If your site has a cross-site scripting bug, an attacker can steal everything in it. So:

  • Never store passwords, payment details or private data.
  • Be careful with authentication tokens. Many security teams prefer HttpOnly cookies for session tokens, because JavaScript cannot read those.
  • Treat everything you read from storage as untrusted input. Someone can edit it in DevTools. Validate it and use textContent when displaying it.

Common mistakes

  • Forgetting to stringify objects. You end up with [object Object].
  • Not parsing on the way out. You get text and not an array.
  • No fallback for null. JSON.parse(null) returns null, and then .length fails.
  • Storing too much. Quotas are small.
  • Using it for secrets. Do not.
  • Assuming the data is valid. An older version of your app may have saved a different shape.

Try it yourself

  1. Build a counter that saves its value in localStorage, so reloading the page keeps the number.
  2. Add a dark mode toggle that remembers the choice.
  3. Save a form draft on every input event and restore it on page load.
  4. Open DevTools, go to Application and then Local Storage, find your keys and edit one by hand. See what your app does.
javascript
localStorage.setItem("theme", "dark");

const theme = localStorage.getItem("theme");
console.log(theme); // "dark"

console.log(localStorage.getItem("missing")); // null

localStorage.removeItem("theme");
localStorage.clear();            // remove everything for this origin
console.log(localStorage.length);

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account