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.