localStorage and sessionStorage

Web Storage provides simple string key-value storage. localStorage persists across browser sessions for an origin, while sessionStorage is scoped to the browser page session. Values are strings, so objects require serialization with JSON.

Storage is synchronous, so large or frequent operations can affect responsiveness. It should not be treated as a secure secret store.

Persisting JSON
const settings = {
  theme: 'dark',
  compact: true
};

localStorage.setItem('settings', JSON.stringify(settings));

const restored = JSON.parse(
  localStorage.getItem('settings') ?? '{}'
);

console.log(restored);
💡 Web Storage stores strings. JSON serialization converts the object into a string and JSON.parse restores the object structure.
Key Takeaways
  • Web Storage stores strings.
  • localStorage persists across sessions for the origin.
  • Do not store highly sensitive secrets in Web Storage merely because it is convenient.
Knowledge Check

What type of value does localStorage fundamentally store?