Offline-first means designing your application to work without a network connection as the default, and enhancing the experience when connectivity is available. Instead of treating offline as an error state, you treat it as a normal mode of operation.
Why Offline-First?
Network connections are unreliable. Users ride elevators, take flights, pass through tunnels, and visit areas with poor coverage. An offline-first app keeps working through all of these situations.
| Approach | Offline Behavior | User Experience |
|---|---|---|
| Online-only | Blank page or error | Frustrating |
| Offline-fallback | Shows cached version of last page | Acceptable |
| Offline-first | Full functionality with sync | Seamless |
IndexedDB for Local Storage
While the Cache API stores request/response pairs, IndexedDB is a full client-side database for structured data.
Setting Up IndexedDB
CRUD with IndexedDB
Using idb for Simpler IndexedDB
The raw IndexedDB API is verbose. The idb library wraps it with promises:
npm install idbSync Queue Pattern
When offline, queue changes locally. When back online, sync with the server.
Background Sync API
The Background Sync API lets the service worker retry failed requests even after the user leaves the page:
Online/Offline Detection
Note that navigator.onLine only tells you if the device has a network interface. It does not guarantee the server is reachable. Always handle network errors gracefully regardless of this property.
Conflict Resolution
When both the client and server modify the same data while offline, you need a conflict resolution strategy:
| Strategy | Description | Best For |
|---|---|---|
| Last write wins | Most recent timestamp overwrites | Simple apps |
| Server wins | Server version always takes priority | Authoritative data |
| Client wins | Client version always takes priority | User-first apps |
| Manual merge | Show both versions, let user choose | Critical data |
Practical Exercise
Build an offline-capable note-taking app:
Key Takeaways
- Offline-first treats the network as an enhancement, not a requirement.
- IndexedDB stores structured data locally; the
idblibrary makes it easier to use. - The sync queue pattern buffers changes offline and replays them when connectivity returns.
- The Background Sync API lets service workers retry failed syncs even after the page is closed.
- Choose a conflict resolution strategy (last write wins, server wins, manual merge) based on your data's criticality.