Data Persistence
๐ง TL;DR โ Browsers give you several different ways to store data on a user's machine โ cookies, localStorage, IndexedDB, and the HTTP cache โ each with different size limits, lifetimes, and use cases.
A page that forgets everything the moment you close the tab isn't very useful. Browsers expose several storage mechanisms so sites can remember things โ from login sessions to entire offline datasets.
๐ช Cookies
Cookies are small pieces of data (about 4KB) that are automatically attached to every HTTP request to the domain that set them. That makes them the classic mechanism for session management, but also the most expensive to overuse โ every cookie rides along on every request.
document.cookie = "theme=dark; max-age=86400; path=/";
โ ๏ธ Warning: Because cookies travel with every request, storing large amounts of data in them slows down every single network call to your site.
๐๏ธ localStorage and sessionStorage
Both store simple key-value string data directly in the browser, without ever being sent over the network.
| localStorage | sessionStorage | |
|---|---|---|
| Lifetime | Until explicitly cleared | Until the tab closes |
| Capacity | ~5โ10MB | ~5โ10MB |
| Shared across tabs? | Yes (same origin) | No, per tab |
| Sent with requests? | No | No |
localStorage.setItem("theme", "dark");
sessionStorage.setItem("draftId", "1234");
๐ฆ IndexedDB
For anything bigger or more structured than key-value strings โ offline datasets, cached API responses, files โ there's IndexedDB, an asynchronous, transactional database built into the browser.
const request = indexedDB.open("notesDB", 1);
request.onupgradeneeded = (e) => {
e.target.result.createObjectStore("notes", { keyPath: "id" });
};
Unlike localStorage, IndexedDB is asynchronous by design, so large reads and writes don't block the main thread โ the same main thread we talked about being precious back in the rendering posts.
โก The HTTP cache
Separate from anything JavaScript controls, the browser also maintains an HTTP cache governed by response headers like Cache-Control and ETag. This is what lets a repeat visit skip the network entirely for unchanged assets.
โก Tip: A well-configured cache means returning visitors can skip straight to parsing and rendering โ no network round trip needed at all.
โ Key takeaways
Cookies: small, automatic, sent with every request โ best for session tokens, not bulk data.
localStorage/sessionStorage: simple key-value storage, synchronous, no network overhead.
IndexedDB: the right tool for structured or large data, and it's async so it won't block rendering.
The HTTP cache works underneath all of this, deciding whether the network is even involved.
With this post, we've now covered all three pillars this series promised: the rendering engine (parsing through compositing), the browser's process architecture, and data persistence โ the full inner workings of how browsers work.
#browsers #webstorage #caching #performance