Garu
Garu

Reputation: 1179

Firebase get and serve data from external API with infrequent changes

I started using Firebase functions to collect data from external APIs because if I did them through the client itself, they were blocked by CORS. So I get the data from the firebase node server with the function.

I have tested and caching the function works fine. If I call the same function during that hour, the firebase function does not execute and returns the cached data.

The code looks like this:

exports.myFunction = functions.https.onRequest((req, res) => {
  cors(req, res, () => {
    axios
      .get("EXTERNAL_API_URL")
      .then(function (response) {
        res.set("Cache-Control", "public, max-age=3600, s-maxage=3600");
        res.send({ data: response.data });
      })
      .catch(function (error) {
        res.end();
      });
  });
});

I wonder if this option is the right one or would it be better to create a scheduled function that every 1h save/edit the string data from external API in a Firestore document. So the users gets the data from Firestore.

What would be the most recommended? Considering that the data from the external APIs will be the same for all users, there are no frequent changes and it's not necessary to be authenticated or logged in to get that data.

Thanks in advance!

Upvotes: 1

Views: 266

Answers (1)

Zeenath S N
Zeenath S N

Reputation: 1170

Given that your data doesn’t change frequently, I think that using caching is better. If you use a scheduled function to store data in Firestore, then you will have to use a query which in turn increases the cost, as the pricing is dependent on the number of queries performed.

You can also use below two methods to avoid returning stale data to your users:

  1. Use s-maxage in set cache control to a lesser time if you are afraid that your user may receive stale content.
  2. You can also use vary header to determine whether the cached content is valid or if the content should be revalidated with the origin server. Firebase hosting does it automatically so that you don’t have to worry about it.

Upvotes: 2

Related Questions