How to get the timestamp from the Firebase server

I will divide this article in two:

  1. Server-side
  2. Client-side

Server-side

Define a function:

javascript
const functions = require('firebase-functions');

exports.getTimestamp = functions.https.onRequest((req, res) => {
        
    return res.send(JSON.stringify({ timestamp: Date.now() }));
    
});

If you want to get the timestamp from a different origin than the website (and avoid CORS errors), you should add cors as a dependency:

javascript
const functions = require('firebase-functions');
const cors      = require('cors')({origin: true});

exports.getTimestamp = functions.https.onRequest((req, res) => {
    
    return cors(req, res, async () => {
        
        res.send(JSON.stringify({ timestamp: Date.now() }));
        
    });
    
});

Now you can deploy the functions:

terminal
firebase deploy --only functions

You get a URL to call the function after deploying it.

Client-side

javascript
const getTimestamp = async () => {
   
    // You get the full URL after deploying the function
    let url = 'https://YOUR_FIREBASE_PROJECT/getTimestamp';
    
    // Fetching the URL
    let res = await fetch(url);
    
    // Getting the result
    let {timestamp} = await res.json();
    
    console.log(timestamp);
    // 1598519554856
  
    return timestamp;
    
}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.