Skip to content
Tutorials Center
My learning

Topics

Lesson 90 of 122 ยท Web APIs

Web Storage

Save data in the browser with localStorage and sessionStorage. Learn the API, storing objects as JSON, the storage event, size limits and privacy rules.

Reload a normal web page and everything your JavaScript created is gone: variables, form input, the open tab of a menu. Web Storage gives each website a small, simple notebook inside the browser where it can write down keyโ€“value pairs and read them back later, even after a reload or a restart.

It is the easiest way to remember things like a dark-mode preference, a half-written comment or the last tab someone opened. In this lesson you will learn the two storage objects, how to store more than plain text, how tabs can react to each other's changes, and what you should never put in storage.

The editors on this page cannot use Web Storage. They run in a sandbox without an origin of their own, so localStorage and sessionStorage throw a SecurityError. The live examples below use a small in-memory stand-in with exactly the same methods. Copy the read-only snippets into an .html file served from localhost to try the real thing.

Two storage areas

The API offers two objects with identical methods. The difference is how long the data lives:

localStorage sessionStorage
Lifetime Until your code or the user deletes it Until the tab is closed
Shared between tabs? Yes, across all tabs and windows of the same origin No, each tab has its own copy
Survives a reload? Yes Yes
Typical use Preferences, saved drafts, "don't show again" flags Multi-step form progress, one-off state for this visit

Both are scoped to an origin: the combination of scheme, host and port. Data saved by https://example.com is invisible to https://shop.example.com and to http://example.com. Each site gets its own private notebook.

The methods

Five methods and one property cover everything:

JavaScript
localStorage.setItem('theme', 'dark');      // save (or overwrite) a value
localStorage.getItem('theme');              // "dark" (or null if missing)
localStorage.removeItem('theme');           // delete one key
localStorage.clear();                       // delete everything for this origin
localStorage.key(0);                        // the name of the first key
localStorage.length;                        // how many keys are stored

getItem() returns null for a key that doesn't exist, so a default value is easy:

JavaScript
const theme = localStorage.getItem('theme') ?? 'light';

You may also see property syntax such as localStorage.theme = 'dark'. It works, but it can collide with built-in names like length or key, so stick with the methods.

A complete example to run locally

This page remembers the visitor's preferred theme. Save it as theme.html, open it from localhost, pick a theme and reload: your choice survives.

HTML
<label>
  Theme
  <select id="theme">
    <option value="light">Light</option>
    <option value="dark">Dark</option>
  </select>
</label>

<script>
  const select = document.getElementById('theme');

  function apply(theme) {
    document.body.style.background = theme === 'dark' ? '#111' : '#fff';
    document.body.style.color = theme === 'dark' ? '#eee' : '#111';
  }

  const saved = localStorage.getItem('theme') ?? 'light';
  select.value = saved;
  apply(saved);

  select.addEventListener('change', () => {
    localStorage.setItem('theme', select.value);
    apply(select.value);
  });
</script>

Using storage safely

Storage can fail even when the object exists. The user may have blocked site data, a browser's private mode may limit it, the storage may be full, or the page may be sandboxed like the editors here. A small wrapper keeps your page working: it tries real storage and silently falls back to memory.

The example below does exactly that. Run it here and it reports the sandbox error, then carries on with the in-memory fallback. Run the same code in a normal page and it uses real localStorage.

Storage with a fallback

Notice Number(...) when reading the count back. That leads to the most important rule of Web Storage.

Everything is a string

Web Storage stores strings only. Whatever you pass to setItem() is converted with String() first. Numbers survive that conversion well enough (you just convert them back), but objects and arrays do not: they become the useless text "[object Object]".

The fix is JSON. Convert to a string with JSON.stringify() when saving and back with JSON.parse() when loading. The example demonstrates the mistake and the fix side by side, using the same string-only behavior as real storage.

Storing objects as JSON

Guard against broken data. A value may have been saved by an older version of your code, or edited by hand in DevTools. Wrap JSON.parse() in try...catch and fall back to defaults if it throws.

You can inspect and edit everything a site has stored in DevTools, under Application โ†’ Local storage (Chrome and Edge) or Storage (Firefox). See Viewing Source and Using DevTools.

The storage event

When one tab changes localStorage, every other tab of the same origin receives a storage event on window. The tab that made the change does not. The event tells you exactly what changed:

JavaScript
window.addEventListener('storage', (event) => {
  console.log(event.key);        // "theme" (null if clear() was called)
  console.log(event.oldValue);   // "light"
  console.log(event.newValue);   // "dark"
  console.log(event.url);        // the page that made the change

  if (event.key === 'theme') {
    apply(event.newValue);       // keep every open tab in sync
  }
});

This is a simple way to keep several open tabs consistent: log out in one tab and the others can react, or switch to dark mode everywhere at once. sessionStorage is private to each tab, so in practice the event is a localStorage feature.

Limits

  • Size. Browsers give each origin roughly 5 MB of Web Storage (the exact amount varies). Writing beyond the limit throws a QuotaExceededError, which is one more reason to wrap writes in try...catch.
  • Speed. The API is synchronous: every call blocks the page until it finishes. That is fine for small values but bad for large data sets. For those, use IndexedDB, which is asynchronous and holds far more.
  • Not available in workers. Web Workers cannot use localStorage or sessionStorage.
  • Strings only, as you saw above.

Privacy and security

Web Storage is convenient, but it is not a safe.

  • Never store secrets. Any JavaScript running on your page can read storage, including a malicious script injected through a cross-site scripting bug. Passwords, credit card numbers and long-lived login tokens do not belong here. Sessions are better handled by the server with secure, HttpOnly cookies that scripts cannot read.
  • Users can see and delete it. Clearing site data, using private windows or privacy extensions all wipe or block storage. Treat stored values as a convenience that may disappear at any time.
  • Shared computers. Data in localStorage stays after the browser closes, so the next person on a library computer could see it. Prefer sessionStorage for anything tied to a single visit.
  • Privacy law. In some regions, storing non-essential data on a visitor's device requires their consent, just like cookies.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A user fills in step one of a checkout form, closes the tab and comes back tomorrow. Which storage would have kept their progress?

    localStorage lasts until it is deleted. sessionStorage is cleared when the tab closes.
  2. 2. What does localStorage.getItem('cart') return after localStorage.setItem('cart', { items: 3 })?

    Web Storage stores strings only, so the object is converted with String(). Use JSON.stringify() when saving and JSON.parse() when loading.
  3. 3. Tab A calls localStorage.setItem('theme', 'dark'). Which tabs receive a storage event?

    The storage event notifies other documents of the same origin. The tab that made the change does not receive it.
  4. 4. Which of these is a sensible thing to keep in localStorage?

    Any script on the page can read storage, so it suits harmless preferences. Secrets belong on the server.

Summary

  • localStorage keeps data until it is deleted; sessionStorage keeps it until the tab closes. Both are private to an origin.
  • Use setItem(), getItem() (returns null when missing), removeItem(), clear(), key() and length.
  • Values are strings: save objects with JSON.stringify() and load them with JSON.parse().
  • Other tabs hear about localStorage changes through the storage event.
  • Expect about 5 MB, synchronous calls and failures; wrap access in try...catch.
  • Never store passwords, tokens or other secrets in Web Storage.

Next lesson: Web Workers, where you move heavy work off the main thread so the page stays smooth.