I will divide this article in two:
Define a function:
javascriptconst 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:
javascriptconst 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:
terminalfirebase deploy --only functions
You get a URL to call the function after deploying it.
javascriptconst 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.