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.")
})
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:
/
) instead of the rewrite. The the cloud function can then serve content only on a known (and cacheable) path.