The Web Storage API is a modern, faster, and more secure way to store data on the client side compared to cookies. It allows web applications to store up to 5MB of data as key-value pairs directly in the user's browser.
Try saving data to your browser's persistent storage. The data will remain even if you refresh the page!
The Web Storage API provides two mechanisms for storing data, differing only in their lifespan:
Data has **no expiration date**. It survives browser restarts and computer reboots. It remains until explicitly deleted via code or cleared by the user.
Data is **temporary**. It is deleted when the specific browser tab or window is closed. Each tab has its own isolated session storage.
Both storage types use the same set of simple methods for data manipulation:
// Syntax: storage.setItem(key, value)
localStorage.setItem("theme", "dark");
sessionStorage.setItem("user_id", "404");
// Syntax: storage.getItem(key)
let myTheme = localStorage.getItem("theme");
console.log(myTheme); // "dark"
// Remove one specific item
localStorage.removeItem("theme");
// Wipe the entire storage for this domain
localStorage.clear();
| Feature | LocalStorage | SessionStorage | Cookies |
|---|---|---|---|
| Expiry | Never | Tab closing | Custom / Closure |
| Capacity | 5MB - 10MB | 5MB | 4KB |
| Server Side | No access | No access | Included in Headers |
JSON.stringify() when saving and JSON.parse() when retrieving.