Firebase Tutorial
- Home
- Introduction
- Project Setup
- Authentication (Email/Pass)
- Social Authentication
- Cloud Firestore (Basics)
- Firestore Queries
- Real-time Updates
- Firestore Security Rules
- Cloud Storage
- Storage Security Rules
- Cloud Functions (Intro)
- Triggering Functions
- Firebase Hosting
- Firebase Analytics
- Crashlytics & Performance
- Remote Config
- App Check
- Offline Persistence
- Firebase with Next.js
- Best Practices
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.fromCacheto 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 stateMobile Perk: In iOS and Android SDKs, offline persistence is enabled by default!