0

We have an application that uses firebase and firestore as database. We want to implement several sections in our application that our customers manage several contents on their website using existing data from application. We want to create an api for them to fetch data on their site. But when we provide data on api we don't want to fetch data from firestore directly because that is costly and unnecessary for mostly static content.

We want to create a headless cms model, the cms ui is our application but how should be store data and serve it. We can think that we can create several cloud functions to save data to somewhere in desired way when data in our application change and we can deploy an express.js node application to google cloud app engine to serve an api. But how should we store data, or is there other ideas that can we consider?

1 Answers1

0

We want to create an api for them to fetch data on their site. But when we provide data on api we don't want to fetch data from firestore directly because that is costly and unnecessary for mostly static content.

The most straight forward way of doing this would be to use a combination of Function & Hosting from Firebase. The nodejs function would provide you a way to getting the data directly from Firestore. The hosting part will basically serve this data from Firestore as a JSON along with an appropriate cache time. Firebase Hosting has CDN built in, so that your Cloud Function will only be called when the cache expires.

const express = require("express");
const cors = require("cors");
const admin = require("firebase-admin");

const page = express();
page.use(cors());

page.get("/endpointName", (request, response) => {
  return admin
    .firestore()
    .collection("name")
    .get()
    .then((docs) => {

      // setting cache time to 7 days
      const cacheTime = 604800;
      response.set(
        "Cache-Control",
        `public, max-age=${cacheTime}, s-maxage=${cacheTime}`
      );

      // Do something with the firestore data -> docs
      // Return the JSON response that you want:
      response.send(...);
    });
});

module.exports = page;

Here's what the firebase.json file could look like -

{
    "hosting": {
      "public": "public",
      "rewrites": [
        {
          "source": "/endpointName",
          "function": "page"
        }
      ],
      "ignore": [
        "firebase.json",
        "**/.*",
        "**/node_modules/**"
      ]
    },
    "functions": {
      "source": "functions"
    }
}