Web storage

Topic 1 of 2 in Browser APIs5 min readBeginnerFree course

Overview

The browser can remember small amounts of data for your site, even after the page is closed. This is how this course remembers which topics you’ve completed — and how many sites remember your theme, a half-written draft, or the last tab you had open.

JavaScript
localStorage.setItem('lastLesson', 'arrow-functions');
localStorage.getItem('lastLesson');   // 'arrow-functions'
localStorage.removeItem('lastLesson');
localStorage.clear();                 // everything for this site

getItem returns null for a key that doesn’t exist, which pairs nicely with ?? for defaults:

JavaScript
const fontSize = Number(localStorage.getItem('fontSize') ?? 16);

localStorage vs sessionStorage

On one site, Tab 1 and Tab 2 each have their own sessionStorage, which is gone when the tab closes. Both share one localStorage, which is kept after a restart. Below, an object is turned into a string with JSON.stringify to be stored, and back into an object with JSON.parse.

localStorage sessionStorage
Lasts until cleared by code or the user the tab is closed
Shared between tabs yes no
Good for preferences, progress, drafts one visit’s state, multi-step forms

Both have exactly the same methods: setItem, getItem, removeItem, clear, key(i) and length.

Storage belongs to an origin — the protocol, domain and port. https://academy.example.com can’t read the storage of https://other.example.com. It also belongs to one browser on one device: progress saved on a laptop isn’t on a phone. For that, you need a server and accounts.

Storing objects

Storage only holds strings, so convert objects with JSON:

JavaScript
const progress = { done: ['loops', 'arrays'], updated: Date.now() };
localStorage.setItem('progress', JSON.stringify(progress));

const saved = JSON.parse(localStorage.getItem('progress') ?? '{}');

Numbers and booleans become strings too: setItem('count', 5) stores '5', and setItem('dark', false) stores 'false' — which is truthy! Convert when reading.

A safe little wrapper

Stored data can be missing, written by an older version of your app, or edited by hand in DevTools. Wrapping storage once protects every caller:

JavaScript
const store = {
  get(key, fallback) {
    try {
      const raw = localStorage.getItem(key);
      return raw === null ? fallback : JSON.parse(raw);
    } catch {
      return fallback; // blocked storage or broken JSON
    }
  },
  set(key, value) {
    try {
      localStorage.setItem(key, JSON.stringify(value));
    } catch {
      // full, or blocked (some private modes) — not worth crashing over
    }
  },
};

const done = store.get('done', []);
store.set('done', [...done, 'web-storage']);

Versioning keys

If the shape of your saved data changes, old saved data won’t fit. Prefixing keys with your app name and a version keeps things tidy: academy:v2:progress. When you change the format, bump the version and ignore (or migrate) the old key.

Reacting to changes in other tabs

When one tab changes localStorage, every other tab of the same site receives a storage event. Use it to keep tabs in sync:

JavaScript
window.addEventListener('storage', (event) => {
  if (event.key === 'theme') {
    document.documentElement.dataset.theme = event.newValue;
  }
});

Things to know

  • Space is limited (about 5 MB per site).
  • Reading and writing is synchronous, so keep the data small.
  • Private browsing and some settings block storage — wrap calls in try…catch.
  • Users can clear it at any time, so treat it as a convenience, never the only copy of something important.
  • DevTools → Application (Chrome/Edge) or Storage (Firefox) shows and lets you edit everything stored.

Not for secrets. Any script on your page can read web storage, so never keep passwords or tokens there.

Other ways to store data

Option Use it for
localStorage / sessionStorage small strings: settings, progress, drafts
Cookies small values the server needs to see on every request (sessions)
IndexedDB large or structured data, files, offline apps
Cache API saved network responses for offline use

For most beginner projects, localStorage is all you need.

Exercise

Remember the theme

Save the chosen theme when the toggle is clicked, and apply the saved theme when the page loads. If nothing is saved, follow the system setting (prefers-color-scheme).

JavaScript
const toggle = document.querySelector('#theme-toggle');

Summary

  • localStorage keeps data until it’s cleared; sessionStorage until the tab closes.
  • Storage is per site (origin) and per browser — it doesn’t follow the user to another device.
  • Values are always strings — use JSON for objects, and handle missing or broken data.
  • The storage event tells other tabs when localStorage changes.
  • Never store passwords or other secrets in web storage.