0
0
Firebasecloud~5 mins

Server timestamps in Firebase - Commands & Configuration

Choose your learning style9 modes available
Introduction
When you save data to Firebase, you often want to record the exact time the data was saved. Server timestamps let Firebase automatically add the current time from its servers, so you get a reliable and consistent time value.
When you want to record when a user created or updated a record without relying on the user's device clock.
When multiple users update data and you want a consistent timeline of changes.
When you need to sort or filter data by the time it was saved on the server.
When you want to avoid errors caused by incorrect device times.
When you want to track event times in a chat app or activity log.
Commands
This command sets the lastLogin field of the user123 document to the server timestamp. It tells Firebase to save the current server time automatically.
Terminal
firebase firestore:documents set users/user123 '{"lastLogin": FieldValue.serverTimestamp()}'
Expected OutputExpected
✔ Document users/user123 successfully written.
This command retrieves the user123 document to verify that the lastLogin field contains the server timestamp value.
Terminal
firebase firestore:documents get users/user123
Expected OutputExpected
{ "lastLogin": { "_seconds": 1685600000, "_nanoseconds": 0 } }
Key Concept

If you remember nothing else from this pattern, remember: use Firebase's serverTimestamp() to get a reliable time from the server, not the user's device.

Common Mistakes
Setting the timestamp field to the device's current time instead of using serverTimestamp()
Device clocks can be wrong or tampered with, causing inconsistent or incorrect timestamps.
Always use FieldValue.serverTimestamp() to let Firebase set the time on the server side.
Trying to set serverTimestamp() as a string instead of using the FieldValue method
Firebase expects a special FieldValue object, not a plain string, so the timestamp won't be set correctly.
Use the FieldValue.serverTimestamp() method provided by Firebase SDK or CLI.
Summary
Use FieldValue.serverTimestamp() to save the current server time automatically.
Set the timestamp field when writing data to ensure consistent and reliable time values.
Verify the timestamp by reading the document after saving.