How LocalStorage and SessionStorage work

Both are part of the Web Storage API introduced with HTML5. Each is a key-value store reachable only from JavaScript in the browser.

// Writing
localStorage.setItem('userId', 'anon_a3f7c2');
localStorage.setItem('recentlyViewed', JSON.stringify([101, 205, 98]));

// Reading
const userId = localStorage.getItem('userId');
const viewed = JSON.parse(localStorage.getItem('recentlyViewed'));

// Removing
localStorage.removeItem('recentlyViewed');

SessionStorage behaves identically, except the data lives only until the tab is closed.

Comparing the storage mechanisms

Property LocalStorage SessionStorage Cookie
Lifetime Until explicitly removed Until the tab closes Configurable
Sent to the server No No Automatically
Limit 5-10 MB 5-10 MB 4 KB
Readable from JS Yes Yes Yes (unless HttpOnly)
Protection against XSS No No The HttpOnly flag

Use in e-commerce

LocalStorage is a convenient client-side cache for user data that need not travel to the server on every request:

  • Recently viewed products — the block renders instantly with no server call
  • An anonymous identifier — for personalization before the shopper signs in
  • Filter settings — so the visitor does not lose their choices on reload
  • A cart draft — a backup in case the session fails

Tip: when personalizing for signed-out visitors, keep the anonymous identifier in LocalStorage. On sign-in, merge the anonymous history into the profile through identity resolution.

Limits and security concerns

LocalStorage is vulnerable to cross-site scripting: any injected script reads everything in it. Do not use it for sensitive data — tokens or personal information. HttpOnly cookies or server-side sessions suit those purposes.

The second limit is capacity: 5-10 MB. Storing larger structures — an extended browsing history, an offline catalogue — calls for IndexedDB.