'Firebase Realtime Database Timestamp

I'm trying to include a timestamp as I add messages to the Firebase Realtime Database. I have found many similar questions posted, but none of the proposed solutions are working. I'm wondering if I am doing something wrong before I attempt to add the timestamp, maybe my config or something.

Here is my configuration:

import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js';
import { getDatabase, ref, push, set, onValue, query, orderByChild } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-database.js";

const firebaseConfig = {
    ...
};
  
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);

And here is my code when I try to add a message to my messages collection:

const messageListRef = ref(database, 'messages');
const newMessageRef = push(messageListRef);

set(newMessageRef, {
    'name': name.value,
    'message': message.value,
    'createdAt': firebase.database.ServerValue.TIMESTAMP
});

The error I'm receiving it:

index.js:31 Uncaught ReferenceError: firebase is not defined
at HTMLButtonElement.<anonymous>

I have also tried:

  • app.database.ServerValue.TIMESTAMP
  • database.ServerValue.TIMESTAMP

And many others that I can't remember.

Any help would be very much appreciated.



Solution 1:[1]

In Firebase v9+, you need to use serverTimestamp():

import { getDatabase, ref, push, set, onValue, query, orderByChild, serverTimestamp } from "https://www.gstatic.com/firebasejs/9.0.0/firebase-database.js";

/* ... */

set(newMessageRef, {
    'name': name.value,
    'message': message.value,
    'createdAt': serverTimestamp()
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 samthecodingman