Search code examples
firebasegoogle-cloud-functionsfirebase-hosting

Is it possible to cache Cloud Function invocation result in Firebase Hosting rewrite indepedently of the requested URL?


I'm rewriting multiple paths in Firebase Hosting to a Cloud Function that always returns the same result. I need to invoke the function once, cache its result, and return it for any subsequent requests to any of these paths. However, as the documentation states, the cached content is served based on:

  • The hostname
  • The path
  • The query string
  • The content of the request headers specified in the Vary header

So, if a different URL is requested, the function will be invoked again. But is there a way to avoid that? Setting the Cache-Control header does prevent the function from invoking again when the same URL is requested, but not when a different one is.


Here is my Hosting and Functions configuration:

firebase.json:

{
  "hosting": {
    "rewrites": [
      {
        "source": "**",
        "function": "myFunction"
      }
    ]
  }
}

functions/index.ts:

import * as functions from "firebase-functions"

export const myFunction = functions.https.onRequest((req, res) => {
    res.set("Cache-Control", "public, max-age=31536000")
    res.send("This is a Cloud Function.")
})

Solution

  • The caching behavior of Firebase Hosting (and web browsers) is always dependent on the URL path.

    There are a couple ways you could try to work around this, depending on your goals:

    1. Use a redirect (for instance, to /) instead of the rewrite. The the cloud function can then serve content only on a known (and cacheable) path.
    2. Serve a static page instead of a cloud function on every path, then have that static page use javascript to call your cloud function on a known, cached path. The initial static page wouldn't be cached, but it should be faster than a function.