What is Offline-First?
Offline-first means your application works fully offline, storing data locally first, then syncing to the network when available. GUN is designed with offline-first principles at its core:- ✅ Works completely offline
- ✅ No connection required to read/write data
- ✅ Automatic sync when back online
- ✅ No code changes needed
Traditional databases require a connection to a server. GUN stores data locally first, making it instantly available without network latency.
Local-First Architecture
How It Works
GUN stores data in multiple layers:- In-Memory: Data lives in RAM for instant access
- localStorage: Persists < 5MB across browser restarts
- IndexedDB: Stores larger datasets (50MB+)
- Network: Syncs with other peers when online
Reading Data
GUN reads from the fastest available source:Writing Data
GUN writes to all layers simultaneously:Writes are non-blocking. Your app continues immediately while GUN handles persistence in the background.
localStorage Adapter
Fromsrc/localStorage.js:15, GUN automatically uses localStorage:
Browser Persistence
Storage Limits
localStorage has a 5MB limit (per origin):IndexedDB for Large Data
For datasets > 5MB, use the RAD (Radix Storage) adapter:- 50MB+ storage (browser dependent, can be GBs)
- Faster read/write than localStorage
- Better performance for large datasets
Node.js Persistence
On servers, GUN persists to the file system:Offline Capabilities
Scenario 1: Start Offline
Scenario 2: Lose Connection
Scenario 3: Sync After Offline
GUN uses CRDTs (Conflict-free Replicated Data Types) to automatically resolve conflicts when syncing. Learn more in CRDT Concepts.
Sync Strategies
Immediate Sync (Default)
Batched Sync
src/mesh.js:38, GUN batches messages:
Lazy Sync
Building Offline-First Apps
Example 1: Offline Todo List
Example 2: Offline Notes App
Example 3: Progressive Web App
Detecting Online/Offline
Conflict Resolution
When multiple devices make offline changes, GUN resolves conflicts automatically:GUN’s CRDT implementation ensures eventual consistency - all peers eventually agree on the same state.
Best Practices
1
Always assume offline
Design your app to work offline-first. Network is a bonus, not a requirement.
2
Show sync status
Let users know when they’re offline and when data has synced.
3
Handle conflicts gracefully
CRDTs resolve most conflicts, but consider app-specific logic for important data.
4
Test offline scenarios
Use Chrome DevTools to simulate offline conditions during development.
Performance Tips
Lazy Loading
Pruning Old Data
Selective Persistence
Storage Adapters
Available Adapters
localStorage
Built-in, 5MB limit, good for small apps
IndexedDB (RAD)
50MB+, better performance, install separately
File System (Node)
Unlimited, server-side persistence
Amazon S3
Cloud storage adapter for production
Custom Adapter
Next Steps
CRDT
Learn how GUN resolves conflicts
Storage Adapters
Explore storage options