← Lessons

quiz vs the machine

Silver1020

Frontend

The Local and Session Storage

Persist small key value data in the browser, and know which storage to pick.

3 min read · intro · beat Silver to climb

Two simple stores

The Web Storage API offers two synchronous key value stores scoped to an origin.

  • localStorage persists until explicitly cleared, surviving browser restarts
  • sessionStorage lasts only for the lifetime of the tab or page session
  • Both store strings only, so objects must be serialised with JSON stringify

The basic operations

Both share the same interface: setItem, getItem, removeItem, and clear. Keys and values are always strings, and getItem returns null for a missing key.

Limits and gotchas

  • Capacity is roughly five to ten megabytes per origin
  • Access is synchronous, so large reads can block the main thread
  • It is not secure storage, so never store tokens or secrets there
  • Writing fires a storage event in other tabs of the same origin

Choosing between them

Use localStorage for preferences like theme that should persist. Use sessionStorage for transient per tab state like a multi step form in progress.

Key idea

Web Storage holds string key value pairs per origin; localStorage persists indefinitely while sessionStorage clears when the tab closes.

Check yourself

Answer to earn rating on the learn ladder.

1. What is the key difference between localStorage and sessionStorage?

2. How must you store an object in Web Storage?