What is the Web Storage API and how do localStorage and sessionStorage differ?

· Category: HTML & CSS

Short answer

The Web Storage API stores key-value pairs in the browser. localStorage persists until explicitly deleted, while sessionStorage lasts only for the page session.

Key differences

  • localStorage: Survives tab closes and browser restarts; shared across tabs from the same origin.
  • sessionStorage: Cleared when the tab or window is closed; scoped to a single tab.
  • Both store strings only, have a roughly 5-10MB limit, and are synchronous and origin-scoped.

Example

localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme');
localStorage.removeItem('theme');

sessionStorage.setItem('draft', JSON.stringify({ title: 'Hello' }));
const draft = JSON.parse(sessionStorage.getItem('draft'));

Tips

  • Do not store sensitive data like tokens in Web Storage because it is accessible via JavaScript and vulnerable to XSS.
  • Use JSON.stringify and JSON.parse for objects.
  • Listen for the storage event to sync data across tabs using localStorage.