I'm building a Flutter app with offline support using Firestore. My Firestore rules allow only signed-in users to read and write data:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
I have enabled persistence in Firestore with the following settings:
final firestore = FirebaseFirestore.instance;
firestore.settings = const Settings(
persistenceEnabled: true,
cacheSizeBytes: Settings.CACHE_SIZE_UNLIMITED,
);
In my app, User A makes offline writes using a WriteBatch. If User A logs out before going back online and I log in as User B on the same device, the offline data is not synced to Firestore. It only syncs if I log back in as User A.
Here’s a simplified version of the code:
WriteBatch batch = firestore.batch();
String datePurchase = DateFormat('yyyyMMdd').format(purchaseTime);
try {
batch.set(
firestore.collection('foo/$foo/bar/$bar/hello/$hello/test').doc(),
{'time': myTime, 'integrityCount': FieldValue.increment(1)},
);
batch.set(
firestore.collection("hello/$hello/you").doc(cId),
{
'remaining': FieldValue.increment(-totalRaw),
'lastModified': FieldValue.serverTimestamp(),
},
SetOptions(merge: true),
);
await batch.commit();
} catch (e) {
return Future.error('FIRESTORE_ERROR');
}
Log out function:
await FirebaseAuth.instance.signOut();
My Questions
Is the Firestore rule causing this behavior?
No.
Does it reject syncing data created by a different user after login?
No, that's not what's happening here. It's not the rules, it's the SDK.
How can I ensure offline data syncs to Firestore even after a user logs out and a different user logs in, while securing the Firestore rule?
Unfortunately, you can't. When the Firebase SDK sees that a new user is signed in that's different than the prior one, it can't go back and synchronize any pending changes. The prior user's data is completely wiped out and unavailable for use. The new current user would not be able to authenticate as the prior user, which means there is no guarantee (and no attempt) that security rules (nor downstream processing of any Firestore Cloud Functions) would be able to process any pending write as it was intended (authenticated as the prior user, using their ID token).
Firestore's offline persistence was only meant to handle cases where internet connectivity is only briefly unavailable, and it doesn't support multiple concurrent users for data sync. If you think it should, you can contact Firebase support to file a feature request, but I highly doubt they will accept it due to the complexity of the problem combined with a lack of desire for it.