How to Use Server Timestamp in Firestore for Accurate Time
Use
firebase.firestore.FieldValue.serverTimestamp() to set a field to the current server time in Firestore. This ensures the timestamp is generated by the server, not the client device, keeping your data consistent and accurate.Syntax
The syntax to use the server timestamp in Firestore is:
firebase.firestore.FieldValue.serverTimestamp(): This function returns a special value that tells Firestore to insert the current server time when writing the document.
javascript
const timestamp = firebase.firestore.FieldValue.serverTimestamp();Example
This example shows how to add a new document to a Firestore collection with a field set to the server timestamp. The timestamp will be the exact time the server processes the write.
javascript
import { initializeApp } from 'firebase/app'; import { getFirestore, collection, addDoc, serverTimestamp } from 'firebase/firestore'; // Your Firebase config const firebaseConfig = { apiKey: 'YOUR_API_KEY', authDomain: 'YOUR_AUTH_DOMAIN', projectId: 'YOUR_PROJECT_ID', }; // Initialize Firebase const app = initializeApp(firebaseConfig); const db = getFirestore(app); async function addMessage() { try { const docRef = await addDoc(collection(db, 'messages'), { text: 'Hello, Firestore!', createdAt: serverTimestamp() }); console.log('Document written with ID:', docRef.id); } catch (e) { console.error('Error adding document:', e); } } addMessage();
Output
Document written with ID: <generated_document_id>
Common Pitfalls
Common mistakes when using server timestamps include:
- Expecting the timestamp field to have a value immediately after setting it. It is initially
nulluntil the server writes the actual time. - Using client-side timestamps like
Date.now()which can cause inconsistent times due to client clock differences. - Not handling
nullvalues when reading documents that have pending server timestamps.
javascript
/* Wrong way: Using client time */ const wrongTimestamp = new Date(); /* Right way: Using server timestamp */ const rightTimestamp = firebase.firestore.FieldValue.serverTimestamp();
Quick Reference
Summary tips for using Firestore server timestamps:
- Use
serverTimestamp()to get consistent, trusted timestamps. - Handle
nullvalues in your app UI when timestamps are pending. - Use timestamps for created/updated fields to track changes reliably.
Key Takeaways
Use firebase.firestore.FieldValue.serverTimestamp() to set server-generated timestamps.
Server timestamps ensure consistent and accurate time regardless of client device clocks.
Timestamp fields may be null initially until the server writes the actual time.
Avoid using client-side time functions for timestamps in Firestore.
Always handle possible null timestamp values when reading documents.