Offline Persistence
Firebase apps naturally handle network interruptions, but you can explicitly enable disk persistence to allow data to survive app restarts and reboots, even without a connection.
1. Firestore Persistence (Web)
On web, persistence is not enabled by default. You must call enableIndexedDbPersistence.
import { getFirestore, enableIndexedDbPersistence } from "firebase/firestore";
const db = getFirestore();
enableIndexedDbPersistence(db).catch((err) => {
if (err.code == 'failed-precondition') {
// Multiple tabs open, persistence can only be enabled in one tab at a time.
console.log("Persistence failed (multiple tabs)");
} else if (err.code == 'unimplemented') {
// The current browser does not support persistence.
console.log("Persistence is not supported");
}
});
2. How it Works
- Caching: Queries are served from the local cache when offline.
- Syncing: Once the device comes back online, local changes are sent to the server automatically.
- Metadata: You can check
doc.metadata.fromCache to see if the data is live or local.
3. Realtime Database Persistence
For the Realtime Database, simple persistence is enabled like this:
firebase.database().goOffline(); // Manually manage state
Mobile Perk: In iOS and Android SDKs, offline persistence is enabled by default!