Skip to content

Firestore Offline Data — Enabling Persistent Local Data for Mobile and Web Apps

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about Firestore Offline Data. We cover key concepts, practical examples, and best practices to help you master this topic.

Firestore offline persistence allows your application to read and write data even when the device is offline, storing data locally and synchronizing changes when connectivity is restored.

What You'll Learn

  • Enabling disk and memory persistence
  • Reading from cache during offline periods
  • Handling pending writes and conflicts

Why It Matters

Offline support is critical for mobile apps and unreliable networks. Without offline persistence, users lose access to data and cannot create content. DodaTech's mobile apps rely on Firestore offline persistence for uninterrupted threat monitoring.

flowchart TD
    A["Online"] --> B["Read from server"]
    A --> C["Write to server"]
    B --> D["Cache locally"]
    C --> E["Pending write queue"]
    D --> F["Offline"]
    E --> F
    F --> G["Read from cache"]
    F --> H["Queue writes locally"]
    G --> I["Display cached data"]
    H --> J["Sync when online"]

Code Examples

// Enable offline persistence
import { initializeFirestore, CACHE_SIZE_UNLIMITED } from 'firebase/firestore';
import { getFirestore } from 'firebase/firestore';

// Enable with unlimited cache
const db = initializeFirestore(app, {
  cacheSizeBytes: CACHE_SIZE_UNLIMITED
});

// Or with specific cache size
const db2 = initializeFirestore(app, {
  cacheSizeBytes: 100 * 1024 * 1024  // 100 MB
});

// Enable for Web (indexedDB persistence)
import { enableMultiTabIndexedDbPersistence } from 'firebase/firestore';

enableMultiTabIndexedDbPersistence(db).catch((err) => {
  if (err.code === 'failed-precondition') {
    console.log('Multiple tabs open, persistence in single tab mode');
  } else if (err.code === 'unimplemented') {
    console.log('Browser does not support persistence');
  }
});
// Handling offline state
import { onSnapshot, doc } from 'firebase/firestore';

// Listen with metadata to detect cache vs server
const unsubscribe = onSnapshot(
  doc(db, 'users', 'user123'),
  { includeMetadataChanges: true },
  (snapshot) => {
    const source = snapshot.metadata.fromCache ? 'local cache' : 'server';
    const hasPending = snapshot.metadata.hasPendingWrites;
    console.log(`Data came from ${source}`);
    console.log(`Has pending writes: ${hasPending}`);

    if (snapshot.metadata.fromCache) {
      showOfflineIndicator(true);
    } else {
      showOfflineIndicator(false);
    }

    // Update UI
    updateUI(snapshot.data());
  }
);

// Detect online/offline
window.addEventListener('online', () => {
  console.log('Back online - syncing changes');
});

window.addEventListener('offline', () => {
  console.log('Offline - using cached data');
});
# Python Firestore offline persistence
from google.cloud import firestore

# Note: Python Admin SDK does not have offline persistence
# This is a client-side feature for web/mobile
# Use local caching strategies instead:

class LocalCache:
    def __init__(self):
        self.cache = {}

    def get_with_cache(self, doc_ref):
        doc_id = doc_ref.path
        if doc_id in self.cache:
            return self.cache[doc_id]
        doc = doc_ref.get()
        self.cache[doc_id] = doc.to_dict() if doc.exists else None
        return self.cache[doc_id]
// Write operations while offline
// These queue locally and sync when online
async function saveWhileOffline(userId, data) {
  const ref = doc(db, 'users', userId);
  await setDoc(ref, data);
  // Even if offline, this returns immediately
  // The write is queued locally
  console.log('Write queued for sync');
}

// Wait for pending writes to sync
import { waitForPendingWrites } from 'firebase/firestore';
await waitForPendingWrites(db);
console.log('All pending writes synced');

Common Mistakes

1. Not Enabling Persistence Explicitly

Persistence is not enabled by default. You must call enableIndexedDbPersistence.

2. Setting Cache Size Too Low

Default cache is 40 MB. Increase for apps with large local datasets.

3. Ignoring Pending Write State

Show pending indicators to users so they know data is not yet synced.

4. Not Handling Conflict Resolution

Server writes during offline periods may conflict. Design data models that minimize conflicts.

5. Assuming All Platforms Support Persistence

Node.js Admin SDK and React Native have different persistence capabilities.

Practice Questions

  1. How do you enable offline persistence for Firestore?
  2. What happens to writes performed while offline?
  3. How do you detect if data came from cache or server?
  4. What is the default cache size?
  5. How do you wait for all pending writes to sync?

Answers:

  1. Call enableIndexedDbPersistence() before any other Firestore operations.
  2. Writes are queued locally and synchronized when connectivity is restored.
  3. Check snapshot.metadata.fromCache.
  4. 40 MB.
  5. Call waitForPendingWrites(db).

Challenge: Build a task management app that works fully offline. Implement persistence, show offline/online indicators, display pending write counts, and handle conflict resolution when the same task is edited by multiple users offline.

FAQ

Does offline persistence work in all browsers?

Persistence uses IndexedDB, which is supported in all modern browsers. Older browsers like IE 10 and below do not support it.

What happens if the cache exceeds the configured size?

Firestore evicts the least recently used documents when the cache exceeds the configured size.

Can I access the local cache directly?

No. Firestore manages the cache internally. You access cached data through normal Firestore queries.

How does conflict resolution work with offline writes?

Firestore uses last-write-wins conflict resolution. Design data models with timestamps or version fields for custom conflict resolution.

Does offline persistence work with real-time listeners?

Yes. Real-time listeners continue to work offline by reading from the local cache. They automatically switch to server updates when online.

Mini Project

Build a note-taking app with full offline support. Enable persistence, cache note data locally, mark pending writes visually, sync changes when online, handle conflicts by showing both versions, and display network status.

What's Next

Learn about Firestore pagination with cursors for large result sets, then explore Firebase Authentication with email and password.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro