0
0
FirebaseHow-ToBeginner · 3 min read

How to Use Firestore Offline: Enable and Use Offline Persistence

To use Firestore offline, enable offline persistence by calling enableIndexedDbPersistence() on your Firestore instance. This allows your app to read and write data locally when offline, syncing changes automatically when back online.
📐

Syntax

Enable offline persistence by calling enableIndexedDbPersistence() on your Firestore instance before any other Firestore operations. This method returns a promise that resolves when persistence is enabled.

Example parts:

  • firebase.firestore(): Gets the Firestore instance.
  • enableIndexedDbPersistence(): Enables offline data storage.
  • catch(): Handles errors like multiple tabs open.
javascript
import { initializeApp } from 'firebase/app';
import { getFirestore, enableIndexedDbPersistence } from 'firebase/firestore';

const firebaseConfig = {
  // your config here
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

enableIndexedDbPersistence(db)
  .catch((err) => {
    if (err.code === 'failed-precondition') {
      // Multiple tabs open, persistence can only be enabled in one tab
      console.log('Persistence failed: Multiple tabs open');
    } else if (err.code === 'unimplemented') {
      // The browser does not support all features required
      console.log('Persistence is not available');
    }
  });
💻

Example

This example shows how to enable offline persistence and add a document to Firestore. The data will be saved locally if offline and synced when back online.

javascript
import { initializeApp } from 'firebase/app';
import { getFirestore, enableIndexedDbPersistence, collection, addDoc, getDocs } from 'firebase/firestore';

const firebaseConfig = {
  // your config here
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

// Enable offline persistence
enableIndexedDbPersistence(db).catch((err) => {
  if (err.code === 'failed-precondition') {
    console.log('Persistence failed: Multiple tabs open');
  } else if (err.code === 'unimplemented') {
    console.log('Persistence is not available');
  }
});

async function addAndReadData() {
  try {
    // Add a document
    await addDoc(collection(db, 'messages'), {
      text: 'Hello offline Firestore!',
      timestamp: Date.now()
    });

    // Read documents
    const querySnapshot = await getDocs(collection(db, 'messages'));
    querySnapshot.forEach((doc) => {
      console.log(doc.id, '=>', doc.data());
    });
  } catch (e) {
    console.error('Error adding or reading document:', e);
  }
}

addAndReadData();
Output
messages collection document IDs and data printed in console, including the newly added message
⚠️

Common Pitfalls

Common mistakes when using Firestore offline include:

  • Calling enableIndexedDbPersistence() after Firestore operations start, which prevents persistence from enabling.
  • Opening multiple tabs with persistence enabled, causing failed-precondition errors.
  • Using browsers that do not support IndexedDB, leading to unimplemented errors.
  • Not handling synchronization conflicts properly when back online.

Always enable persistence once at app start and handle errors gracefully.

javascript
/* Wrong: enabling persistence after Firestore usage */
const db = getFirestore(app);
// Firestore operations start here
const col = collection(db, 'test');
// Then enable persistence (too late)
enableIndexedDbPersistence(db).catch(console.error);

/* Right: enable persistence before any Firestore usage */
enableIndexedDbPersistence(db).then(() => {
  // Now safe to use Firestore
  const col = collection(db, 'test');
});
📊

Quick Reference

  • Enable persistence: Call enableIndexedDbPersistence(db) once at app start.
  • Handle errors: Watch for failed-precondition and unimplemented codes.
  • Offline reads/writes: Firestore caches data locally and syncs automatically.
  • Multiple tabs: Persistence works in only one tab at a time.

Key Takeaways

Enable offline persistence by calling enableIndexedDbPersistence() before any Firestore operations.
Offline persistence caches data locally, allowing reads and writes without internet.
Handle errors for multiple tabs and unsupported browsers to avoid persistence failures.
Firestore syncs local changes automatically when the device reconnects to the internet.
Only one browser tab can have persistence enabled at a time to prevent conflicts.