Choose and observe storage
Choose storage from the job
Match cookies, Web Storage, IndexedDB, Cache Storage, and OPFS to the shape and destination of the data.
Pick the smallest API that fits the job. Small means “fits the data”, not “the one I already know”.
With the inventory from lesson 1 and the boundaries from lesson 2, we can fill in the API column.
The map
One line per API:
- cookie: the browser must send a small value to the server with matching HTTP requests
localStorage: a small string that should survive a browser restartsessionStorage: a small string that belongs to one tab- IndexedDB: structured records, possibly many, that you need to look up by key or index
- Cache Storage: request and response pairs, usually for offline use
- OPFS (origin private file system): file bytes, often large
Two questions do most of the work. Does the server need it on every request? If yes, cookie. Is it a string, a record, a response, or a file? That picks one of the others.
Applied to the field-notes app
Our six values:
- theme: a small replaceable string, restart should keep it.
localStorage - login session: the server must see it. A cookie
- editor draft: one tab, gone when the tab closes.
sessionStorage - saved notes: records we search by title and date. IndexedDB
- cached manual: fetched pages we read offline. Cache Storage
- attachment: a photo, maybe several megabytes. OPFS
Notice the app ends up using five APIs. That’s normal. Combining them is fine as long as every value has one clear owner and one cleanup rule. Putting everything in one place because it’s convenient is not.
The tempting wrong choices
For each row there’s an alternative that looks easier and costs you later.
Don’t put a large client-only object in a cookie. The browser attaches it to every matching request, so a 3 KB preferences blob becomes 3 KB of upload on every image and every API call. Cookies also cap out around 4 KB each.
Don’t put hundreds of notes in localStorage. Every value must be a string, so you serialize the whole array on every save. And the calls are synchronous: while JSON.stringify and setItem run, the page is frozen. With ten notes nobody notices. With two thousand, the editor stutters on every keystroke.
Don’t store the login token in localStorage either. Any script on the origin can read it. A cookie with HttpOnly can’t be read by JavaScript at all. We’ll build that cookie in the next module.
Do the same for your own app
Take one project you work on. List every stored value and assign an API using the two questions above. For each choice, name the tempting alternative and write one sentence about why it’s wrong.
Lesson completed