Understand the idea

localStorage stores string values for an origin across browser sessions. It is suitable for a small preference such as a chosen colour scheme.

Storage may be unavailable or throw an exception. Keep a working default and handle failures. Data is local to that browser profile and origin, not a synchronised account setting. Avoid storing secrets or sensitive personal data in scripts accessible to the page. The HTTP and HTTPS versions of a site have separate storage. Behaviour on file: URLs is not reliably specified, and private browsing usually removes stored data when its private session ends. Use a local HTTP server when testing.

Read the example

This is a JavaScript fragment. Run it in a browser console or an external script. Supply any HTML or data file named in the example first.

JavaScript · EXAMPLE
try {
  localStorage.setItem("theme", "dark");
  const theme = localStorage.getItem("theme");
  console.log(theme);
} catch {
  console.log("Use the default theme.");
}

A small mistake, explained

What goes wrong

Assuming storage always works can make an optional preference break an essential page interaction.

How to fix it. Wrap storage access in try/catch and provide a default. Validate stored values rather than trusting arbitrary strings.

Try it yourself

Save a preference, reload the page, then remove the key in the Application or Storage panel.

Further reading

HTML Living Standard — Web storage

Original explanation and example prepared for HTML code FYI with AI assistance. Test the code in your own context. How these guides are made.