skip to content

Why does a Cloud Function behind a Firebase Hosting rewrite run on every request and never see the session cookie, and what fixes both?

level: seniorimportance: should knowfreq 28%

answer

  1. the CDN treats dynamic content differently
  2. private by default
  3. s-maxage for the CDN
  4. cookies are stripped
  5. only __session passes

basics

~20 s

Hosting's CDN does not cache function responses unless they say so, and it strips cookies from requests except one named __session. Send Cache-Control: public with s-maxage for shareable pages, and rename the session cookie to __session.

solid answer

~40 s

Firebase Hosting caches static files on its CDN automatically and purges them on each deploy, but content from a Cloud Function or Cloud Run rewrite is not cached by default: Hosting treats it as `Cache-Control: private`, so only the requesting browser may keep it and every other request reaches the function. The function must opt in, for example `res.set("Cache-Control", "public, max-age=300, s-maxage=600")`, where `s-maxage` sets the CDN's lifetime; only `GET` and `HEAD` are cached. For efficient caching, Hosting also strips cookies from requests it forwards to functions, except the one named `__session`, so a cookie called `sid` never arrives. Renaming it `__session` fixes that, and Hosting adds that cookie to the cache key, so one user's cached page is never served to another. Personalised pages should still be sent as `private`.

code

typescript · 15 lines
typescript
import { onRequest } from "firebase-functions/v2/https";

function renderRecipe(path: string, signedIn: boolean): string {
  return `<h1>${signedIn ? "Your view of" : "Recipe"} ${path}</h1>`;
}

export const recipePage = onRequest({ region: "europe-west1" }, (req, res) => {
  // Hosting forwards only the __session cookie to the function.
  const signedIn = (req.get("cookie") ?? "").includes("__session=");
  res.set(
    "Cache-Control",
    signedIn ? "private, no-store" : "public, max-age=300, s-maxage=600"
  );
  res.send(renderRecipe(req.path, signedIn));
});

go deeper

for a junior

Recall that static files are cached automatically, function responses are not, and that only the __session cookie reaches a function behind Hosting.

for a middle

Explain the private default for dynamic content, how public, max-age and s-maxage opt a function response into the CDN, and what the cache key is built from.

for a senior

Diagnose from symptoms: invocations equal to page views, a missing session cookie, a stale page after an edit, a lingering 404; fix each with headers, cookie naming or cache lifetimes.

for a principal

Decide which pages a team renders on the server behind Hosting at all, and set a caching policy per page class that balances function cost, freshness and the risk of serving personal content.

## Two kinds of content on Hosting Firebase Hosting sits behind a global **CDN** (content delivery network, a fleet of edge caches). It treats two kinds of response differently. - **Static content**, the files you deploy from `public`, is cached on the CDN automatically. Every deploy clears that cache, so new requests see the new files without any purge step. - **Dynamic content**, responses produced by a Cloud Function or a Cloud Run service behind a rewrite, can differ per user or per request. Hosting therefore does **not** cache it on the CDN by default. The second rule is why a function serving recipe pages runs on every single request, even for anonymous visitors reading the same public recipe. ## Opting dynamic content into the CDN By default Hosting sets `Cache-Control` to `private` for dynamic content, which allows only the requesting browser to keep a copy. To let the CDN cache it, the function sets the header itself: ```typescript res.set("Cache-Control", "public, max-age=300, s-maxage=600"); ``` - `public` lets shared caches, including Hosting's CDN, store the response. - `max-age` is the browser's lifetime, and also the CDN's when `s-maxage` is absent. - `s-maxage` overrides `max-age` for shared caches, so here browsers keep the page five minutes and the CDN ten. - Only `GET` and `HEAD` responses are cached; other methods always reach the function. The general meaning of these directives belongs to HTTP caching. What is specific to Hosting is the default: nothing dynamic is cached until the function says `public`. The CDN's cache key is the hostname, path, query string and any request headers named in `Vary`. For dynamic content Hosting adds `Cookie` and `Authorization` to `Vary` by default, so responses that depend on them are kept apart. ## Why the cookie disappears To keep the CDN efficient, Hosting **strips cookies** from requests it forwards to Cloud Functions or Cloud Run. Exactly one name is allowed through: **`__session`**. 1. A browser sends `sid=abc` and `theme=dark` to `/recipes/42`. 2. Hosting matches the function rewrite and forwards the request without those cookies. 3. The function sees no session and renders the signed-out page. Renaming the session cookie to `__session` makes it reach the function. Hosting also makes `__session` part of the cache key, so two users with different session cookies can never receive each other's cached response. The docs advise using it only when the content really depends on the user's authorization. ## Putting it together for the web companion | Page | Cookie | `Cache-Control` from the function | |---|---|---| | Public recipe, signed out | none | `public, max-age=300, s-maxage=600` | | Public recipe, signed in but identical | `__session` | `public`, if the HTML really does not vary | | "My recipes" page | `__session` | `private, no-store` | A cached public response keyed on `__session` is safe, but it gives every signed-in user a separate CDN entry, so the hit rate collapses. Rendering the shared part publicly and loading the personal part from the client is usually cheaper. ## Other Hosting caching behaviour worth knowing - **404s are cached.** A function's 404 for a URL is cached on the CDN for ten minutes, unless the function's own caching headers say otherwise. Publishing a recipe at a path that recently returned 404 can look broken for up to ten minutes. - **`firebase.json` headers.** A `headers` rule can set `Cache-Control` for a path pattern, such as `no-cache, no-store` for a route that must always be fresh. Header patterns are matched against the original request path, before rewrites apply. - **Full path forwarded.** The function receives the original path and query string, `/recipes/42?lang=fr`, so its router must expect the Hosting path. - **Editing data does not purge anything.** A cached dynamic response is served until its `s-maxage` runs out, however the underlying recipe changes, so keep it short for content editors expect to change quickly. ## Diagnosing in production 1. Check the function's invocation count against page views; equal counts mean nothing is cached. 2. Inspect the response's `Cache-Control`: `private` means the function never opted in. 3. Log the incoming `Cookie` header in the function; if it lacks your session cookie, it is not named `__session`. 4. Request the same public page twice from a fresh client: if the function's logs show both requests, check that the response is a `GET`, that it carries `public`, and that no `__session` cookie or header named in `Vary` is splitting the cache key.

  • After adding public, s-maxage=600, an editor fixes a typo in a recipe but the old page keeps appearing. Why, and what are your options?
    The CDN may serve the cached function response for up to `s-maxage` seconds, and changing the recipe in the database tells the CDN nothing. So the old page can live up to ten minutes. Shorten `s-maxage` for content editors change often, include a version in the URL so changed content gets a new cache key, or accept the delay as the price of fewer function invocations.
  • A recipe URL returned 404 from the function a minute before it was published. Why does it still 404 after publishing?
    Hosting's CDN caches a dynamic 404 response for ten minutes by default so repeated requests for a missing URL do not reach the function. Until that entry expires, the CDN keeps serving the cached 404. If the function sets its own caching headers on the 404, those replace the ten-minute default, so a short or no-store lifetime on not-found responses avoids the gap.

  • Hosting caches function responses on the CDN by default, like static files
  • Without s-maxage, the CDN can never cache a function response
  • All browser cookies are forwarded to the function behind a rewrite
  • Using __session lets one user's cached page leak to another user
  • POST responses are cached when Cache-Control says public