Skip to main content
Progressive Web Apps·Lesson 4 of 5

Offline-First Design

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.

ApproachOffline BehaviorUser Experience
Online-onlyBlank page or errorFrustrating
Offline-fallbackShows cached version of last pageAcceptable
Offline-firstFull functionality with syncSeamless

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

Ctrl+Enter
HTML
CSS
JS
Preview

CRUD with IndexedDB

Ctrl+Enter
HTML
CSS
JS
Preview

Using idb for Simpler IndexedDB

The raw IndexedDB API is verbose. The idb library wraps it with promises:

npm install idb
Ctrl+Enter
HTML
CSS
JS
Preview

Sync Queue Pattern

When offline, queue changes locally. When back online, sync with the server.

Ctrl+Enter
HTML
CSS
JS
Preview

Background Sync API

The Background Sync API lets the service worker retry failed requests even after the user leaves the page:

Ctrl+Enter
HTML
CSS
JS
Preview
Ctrl+Enter
HTML
CSS
JS
Preview

Online/Offline Detection

Ctrl+Enter
HTML
CSS
JS
Preview

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:

StrategyDescriptionBest For
Last write winsMost recent timestamp overwritesSimple apps
Server winsServer version always takes priorityAuthoritative data
Client winsClient version always takes priorityUser-first apps
Manual mergeShow both versions, let user chooseCritical data
Ctrl+Enter
HTML
CSS
JS
Preview

Practical Exercise

Build an offline-capable note-taking app:

Ctrl+Enter
HTML
CSS
JS
Preview

Key Takeaways

  • Offline-first treats the network as an enhancement, not a requirement.
  • IndexedDB stores structured data locally; the idb library 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.