HTML Web Storage provides a way for websites to store data in the user’s browser securely and efficiently. It is more powerful than cookies because it offers larger storage capacity, is faster, and does not send data to the server with every request.
Web Storage has two main mechanisms:
Local Storage stores data permanently in the browser until it’s manually cleared by the user or through code.
| Method | Description |
|---|---|
| localStorage.setItem(key, value) | Stores a value |
| localStorage.getItem(key) | Retrieves a value |
| localStorage.removeItem(key) | Removes a specific item |
| localStorage.clear() | Clears all stored data |
<script>
localStorage.setItem("username", "John");
document.write(localStorage.getItem("username"));
</script>
Session Storage stores data temporarily for a single browser session.
| Method | Description |
|---|---|
sessionStorage.setItem(key, value) |
Stores a value |
sessionStorage.getItem(key) |
Retrieves a value |
sessionStorage.removeItem(key) |
Removes one item |
sessionStorage.clear() |
Clears all data |
<script>
sessionStorage.setItem("color", "blue");
alert(sessionStorage.getItem("color"));
</script>
| Feature | Local Storage | Session Storage |
|---|---|---|
| Lifetime | Permanent | Until tab is closed |
| Capacity | 5–10 MB | 5 MB |
| Scope | All tabs from same origin | Only the current tab |