Dates in Cloud Firestore

Dates in Cloud Firestore

Why you should use serverTimestamp and not local dates.

Looking back, learning Cloud Firestore and using it, one of the greatest confusions I had was how serverTimestamp worked, and why in some instances the timestamp of my document would be undefined for a split second.

When writing to Firestore documents, you shouldn't trust your local date, i.e. use new Date() for your dates. The date on the client could have a different date and time on it than what the server expects. A user's clock could be different, and they can even try to intercept and write malicious dates to the server.

You should instead use serverTimestamp(), which would act as a placeholder, and when the write operation is happening on the server, it then inserts what the server time is in that spot.

This way we can keep our dates properly synchronized.