← Lessons

quiz vs the machine

Silver1180

Frontend

Browser Storage Localstorage and Cookies

Where to keep client data and the tradeoffs of each store.

5 min read · intro · beat Silver to climb

Several places to store data

The browser offers a few client storage options, and picking the wrong one causes bugs and security issues. They differ in size, lifetime, and whether they travel to the server.

The main options

  • Local storage keeps string key value pairs with no expiry until cleared. It is per origin and not sent to the server.
  • Session storage is like local storage but scoped to a single tab and cleared when the tab closes.
  • Cookies are small and are automatically attached to every matching request, which is why they suit session tokens.
  • IndexedDB is a larger asynchronous database for structured data and offline apps.

Security notes

  • Mark auth cookies HttpOnly so JavaScript cannot read them, reducing theft from script injection.
  • Do not put secrets in local storage, since any script on the page can read it.
  • Local and session storage are synchronous and block the main thread, so avoid large writes.

Key idea

Use cookies for data the server needs, session or local storage for small client only values, and IndexedDB for large structured data, keeping secrets out of script readable stores.

Check yourself

Answer to earn rating on the learn ladder.

1. Which store is automatically sent with requests to the server?

2. Why mark an auth cookie HttpOnly?

3. How does session storage differ from local storage?