michalstanko
michalstanko

Reputation: 589

Document creation timestamp (server-time) in Firestore

I'm new to firebase and firestore, creating a single-page app, I was wondering how can I store the document creation time with the document, representing the server-side time. When I changed my system time to an incorrect time and then ran the code below, it was storing the same (incorrect) timestamp for both clientDate and serverTimestamp fields.

I tried the following (Firebase JavaScript SDK version 9.0.2):

import { addDoc, collection, Timestamp } from 'firebase/firestore';
import { db } from '../index';

export const storeSomething = async () => {
    const data = {
        clientDate: new Date(),
        serverTimestamp: Timestamp.now(),
    };
    
    const someCol = collection(db, 'somecollection');
    const docRef = await addDoc(someCol, data);
};

Upvotes: 2

Views: 2326

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598668

The Timestamp.now() function returns the current client-side time, so is indeed sensitive to clock skew and manipulation.

To write a server-side timestamp, use:

  • in v9/modular syntax: serverTimestamp()

  • in v8/compat syntax: firebase.firestore.FieldValue.serverTimestamp()

  • in the Admin SDK: admin.firestore.FieldValue.serverTimestamp()

Upvotes: 4

Related Questions