Access data offline | Firestore | Firebase
Access data offline
Stay organized with collections
Save and categorize content based on your preferences.
How do I Enable Offline Support? | Get to know Cloud Firestore #9 - YouTube
How do I Enable Offline Support? | Get to know Cloud Firestore #9
Cloud Firestore supports offline data persistence. This feature caches a copy of the Cloud Firestore data that your app is actively using, so your app can access the data when the device is offline. You can write, read, listen to, and query the cached data.
When the device comes back online, Cloud Firestore synchronizes any local changes made by your app to the Cloud Firestore backend. For multiple changes to the same document, it's last write wins.
To use offline persistence, you don't need to make any changes to the code that you use to access Cloud Firestore data. With offline persistence enabled, the Cloud Firestore client library automatically manages online and offline data access and synchronizes local data when the device is back online.
Configure offline persistence
When you initialize Cloud Firestore, you can enable or disable offline persistence:
- For Android and Apple platforms, offline persistence is enabled by default. To disable
persistence, set the
PersistenceEnabledoption tofalse. - For the web, offline persistence is disabled by default. To enable
persistence, call the
enablePersistencemethod. Cloud Firestore's cache isn't automatically cleared between sessions. Consequently, if your web app handles sensitive information, make sure to ask the user if they're on a trusted device before enabling persistence.
Code Samples
// Memory cache is the default if no config is specified.
initializeFirestore(app);
// This is the default behavior if no persistence is specified.
initializeFirestore(app, {localCache: memoryLocalCache()});
// Defaults to single-tab persistence if no tab manager is specified.
initializeFirestore(app, {localCache: persistentLocalCache(/*settings*/{})});
// Same as `initializeFirestore(app, {localCache: persistentLocalCache(/*settings*/{})})`,
// but more explicit about tab management.
initializeFirestore(app,
{localCache:
persistentLocalCache(/*settings*/{tabManager: persistentSingleTabManager()})
});
// Use multi-tab IndexedDb persistence.
initializeFirestore(app,
{localCache:
persistentLocalCache(/*settings*/{tabManager: persistentMultipleTabManager()})
});
firebase.firestore().enablePersistence()
.catch((err) => {
if (err.code == 'failed-precondition') {
// Multiple tabs open, persistence can only be enabled
// in one tab at a time.
// ...
} else if (err.code == 'unimplemented') {
// The current browser does not support all of the
// features required to enable persistence
// ...
}
});
// Subsequent queries will use persistence, if it was enabled successfully
test.firestore.js
Note: This product is not available on watchOS and App Clip targets.
Configure cache size
When persistence is enabled, Cloud Firestore caches every document received from the backend for offline access. Cloud Firestore sets a default threshold for cache size. After exceeding the default, Cloud Firestore periodically attempts to clean up older, unused documents. You can configure a different cache size threshold or disable the clean-up process completely:
Code Samples
import { initializeFirestore, CACHE_SIZE_UNLIMITED } from "firebase/firestore";
const firestoreDb = initializeFirestore(app, {
cacheSizeBytes: CACHE_SIZE_UNLIMITED
});
fs_setup_cache.js
firebase.firestore().settings({
cacheSizeBytes: firebase.firestore.CACHE_SIZE_UNLIMITED
});
test.firestore.js
Note: This product is not available on watchOS and App Clip targets.
Listen to offline data
While the device is offline, if you have enabled offline persistence, your listeners will receive listen events when the locally cached data changes. You can listen to documents, collections, and queries.
For checking whether you're receiving data from the server or the cache, use the
fromCache property on SnapshotMetadata in your snapshot event. If
fromCache is true, the data came from the cache and might be stale or
incomplete. If fromCache is false, the data is complete and current with the
latest updates on the server.
Code Samples
import { collection, onSnapshot, where, query } from "firebase/firestore";
const q = query(collection(db, "cities"), where("state", "==", "CA"));
onSnapshot(q, { includeMetadataChanges: true }, (snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type === "added") {
console.log("New city: ", change.doc.data());
}
const source = snapshot.metadata.fromCache ? "local cache" : "server";
console.log("Data came from " + source);
});
});
Get offline data
If you get a document while the device is offline, Cloud Firestore returns data from the cache. When querying a collection, an empty result is returned if there are no cached documents. When fetching a specific document, an error is returned instead.
Query offline data
Querying works with offline persistence. You can retrieve the results of queries with either a direct get or by listening, as described in the preceding sections. You can also create new queries on locally persisted data while the device is offline, but the queries will initially run only against the cached documents.
Configure offline query indexes
By default, the Firestore SDK scans all documents in a collection in its local cache when executing offline queries. With this default behavior, offline query performance can suffer when users are offline for long periods of time.
With persistent cache enabled, you can improve the performance of offline queries by allowing the SDK to create local query indexes automatically.
Code Samples
if let indexManager = Firestore.firestore().persistentCacheIndexManager {
// Indexing is disabled by default
indexManager.enableIndexAutoCreation()
} else {
print("indexManager is nil")
}
Disable and enable network access
You can use the method below to disable network access for your Cloud Firestore client. While network access is disabled, all snapshot listeners and document requests retrieve results from the cache. Write operations are queued until network access is re-enabled.
Code Samples
import { disableNetwork } from "firebase/firestore";
await disableNetwork(db);
console.log("Network disabled!");
// Do offline actions
// ...disable_network.js
Note: This product is not available on watchOS and App Clip targets.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies.