Web Storage & Offline
Cookies, localStorage, sessionStorage, and the conceptual comparison with IndexedDB were already covered thoroughly in the separate Browser Storage, Cookies & Security course's first chapter. This chapter assumes that comparison and goes straight to using IndexedDB practically, plus service workers — the piece that course didn't cover, since it's specifically an HTML/web-app capability rather than a browser-security topic.
IndexedDB in Practice
IndexedDB's API is genuinely more verbose than localStorage's simple get/set — it's asynchronous and event-based, reflecting that it's a real database, not a quick key-value store.
- onupgradeneeded fires only when the database is first created, or when the version number is bumped — exactly where schema changes (adding object stores, indexes) belong.
- Object stores are roughly analogous to tables — each with a
keyPathdefining what makes a record unique. - Transactions wrap every read/write — IndexedDB never lets you read or write outside one, ensuring consistency even with concurrent access.
Service Workers — A Programmable Network Proxy
A service worker is a script that runs separately from any page, sitting between your web app and the network — it can intercept every network request a page makes and decide how to respond, including serving a cached response when genuinely offline.
A Minimal Service Worker — Registration and Caching
The fetch handler here implements a simple "cache first" strategy: check the cache, serve it if present, fall back to the real network only if not. With this in place, the listed files remain available even with no network connection at all.
localhost, which is treated as secure for development purposes. This connects directly back to the security course's HTTPS coverage — yet another reason HTTPS isn't optional for a modern site.
Chapter 6 Quick Reference
- IndexedDB — asynchronous, transaction-based; object stores ≈ tables, keyPath defines uniqueness
- onupgradeneeded — fires only on first creation or version bump; the place for schema changes
- Most real projects use a wrapper library (e.g. idb) over the raw, verbose IndexedDB API directly
- Service worker — a separate script intercepting network requests, enabling offline behaviour
- install event + caches.open/addAll — pre-caching essential files
- fetch event + caches.match — deciding cache-vs-network per request, the basis of offline support
- Requires HTTPS (localhost excepted) — same security principle as the cookies/security course
- Next chapter: Progressive Web Apps — manifest.json, installability basics