Browsers have two built-in ways to store data:
⚠️ Don't use either for sensitive information (passwords, credit cards, etc.), since both are vulerable to XSS attacks!
- Data stored there is cleared when the page session ends (i.e., the browser tab/window closes).
- Each tab has its own
sessionStorageobject, independent from the one in other tabs.
- Data stored there has no expiration time.
Exception: If you're in a private tab, then
localStorageis cleared when the last private tab is closed.
- Exception: If you're in a private tab, then
- Storage object is specific to the protocol. (HTTP object is separate from HTTPS.)
localStorage both implement the Storage interface.
Both objects contain a key-value store, which is where data is kept. The keys and values are both type
.length- The number of entries in the Storage object's key-value store.
const numEntries = sessionStorage.length
.setItem(key, value)- Adds the key-value pair to the store.
.getItem(key)- Retrieves the value for the specified key. (Returns
nullif the key doesn't exist.)
const username = sessionStorage.getItem("key")
.removeItem(key)- Removes the key-value pair for the specified key. (If the key doesn't exist, nothing happens.)
.clear()- Removes all key-value pairs from the store.