Web Storage
Web Storage lets a page save small string values in the browser for later use.
What you will learn
- When to choose localStorage or sessionStorage
- How to save, read, and remove a value
- Why stored data is not a secure place for secrets
Two kinds of storage
localStorage- Data remains for the site until it is removed, even after the browser is closed.
sessionStorage- Data belongs to the current tab session and is removed when that session ends.
Basic example
localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme');
localStorage.removeItem('theme');Storage values are strings. Convert JSON explicitly when you need to save an array or object, and handle unavailable storage or quota errors.
Security and privacy
- Do not store passwords, tokens, or other secrets in Web Storage.
- Any script running on the same origin may be able to read the values.
- Do not assume a value is valid just because it came from your own storage; validate it when reading.
- Provide a useful default when storage is disabled or cleared.