HTML5
What are the Different Types of Storage in HTML5?
HTML5 offers several ways to store data on the client (in the user's browser). The main options are Web Storage (localStorage and sessionStorage), IndexedDB, and the older cookies. Each differs in capacity, lifetime, and how the data is sent to the server.
The Storage Options Compared
| Feature | localStorage | sessionStorage | IndexedDB | Cookies |
|---|---|---|---|---|
| Capacity | ~5-10 MB | ~5 MB | Large (hundreds of MB+) | ~4 KB |
| Lifetime | Until cleared | Until tab closes | Until cleared | Set by expiry date |
| Sent to server? | No | No | No | Yes, with every request |
| Data type | Strings | Strings | Structured (objects, files) | Strings |
| Best for | Persistent settings | Per-tab temporary data | Large structured data | Auth tokens, small IDs |
Web Storage: localStorage vs sessionStorage
- localStorage keeps data with no expiry — it survives page reloads and browser restarts until explicitly cleared.
- sessionStorage keeps data only for the lifetime of the tab; closing the tab clears it.
- Both store string key/value pairs and are not sent to the server, unlike cookies.
Runnable Web Storage Example
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Web Storage Demo</title>
</head>
<body>
<h2>localStorage Demo</h2>
<input id="name" placeholder="Enter your name">
<button onclick="save()">Save</button>
<button onclick="load()">Load</button>
<p id="out"></p>
<script>
function save() {
localStorage.setItem("username", document.getElementById("name").value);
document.getElementById("out").textContent = "Saved!";
}
function load() {
var v = localStorage.getItem("username") || "(nothing saved)";
document.getElementById("out").textContent = "Stored name: " + v;
}
</script>
</body>
</html>💡
IndexedDB is for large, structured, queryable data (offline databases). Cookies are tiny and travel with every HTTP request, so keep them small and use them for things like session tokens.
Key Takeaways
- localStorage persists until cleared; sessionStorage lasts one tab session.
- IndexedDB stores large, structured data client-side.
- Cookies are small and sent to the server on every request.
- Web Storage data stays in the browser and is not sent to the server.
