0
0
Firebasecloud~30 mins

Server timestamps in Firebase - Mini Project: Build & Apply

Choose your learning style9 modes available
Server timestamps
📖 Scenario: You are building a simple chat app using Firebase. Each message needs to have a timestamp showing when it was sent. To keep the time consistent for all users, you want to use Firebase's server timestamp feature instead of the user's device time.
🎯 Goal: Create a Firebase Firestore document for a chat message that includes a server-generated timestamp.
📋 What You'll Learn
Create a dictionary called message with a text field set to 'Hello, Firebase!'.
Add a field called timestamp using Firebase's server timestamp placeholder.
Write code to add the message dictionary to a Firestore collection called messages.
Ensure the timestamp uses Firebase's server time, not the client device time.
💡 Why This Matters
🌍 Real World
Using server timestamps ensures all chat messages have consistent and trustworthy time data regardless of user device clocks.
💼 Career
Understanding server timestamps is essential for backend consistency in cloud applications, especially in real-time databases and messaging apps.
Progress0 / 4 steps
1
Create the message dictionary
Create a dictionary called message with a key text and value 'Hello, Firebase!'.
Firebase
Need a hint?

Use curly braces to create a dictionary and set the key 'text' to the string 'Hello, Firebase!'.

2
Import Firebase server timestamp
Import firestore from firebase_admin and assign firestore.SERVER_TIMESTAMP to a variable called timestamp.
Firebase
Need a hint?

Use firestore.SERVER_TIMESTAMP to get the server timestamp sentinel value.

3
Add timestamp to message dictionary
Add a key timestamp to the message dictionary and set its value to the variable timestamp.
Firebase
Need a hint?

Use dictionary key assignment to add the timestamp to the message.

4
Add message to Firestore collection
Write code to add the message dictionary to the Firestore collection called messages using db.collection('messages').add(message). Assume db is the Firestore client instance.
Firebase
Need a hint?

Use the Firestore client db to add the message to the 'messages' collection.