skip to content

In Firebase Hosting's firebase.json, how does the SPA fallback rewrite to /index.html work, and what can a careless catch-all rewrite break?

level: middleimportance: must knowfreq 55%

answer

  1. rewrite, not redirect
  2. only when no file exists
  3. redirects, static, rewrites, then 404
  4. first matching rule wins
  5. missing chunks come back as HTML

basics

~20 s

A catch-all rewrite whose destination is /index.html serves the app shell for any path that has no deployed file. Careless catch-alls hide 404.html, shadow function rewrites listed after them, and answer missing script requests with HTML.

solid answer

~50 s

In `firebase.json` you add a `rewrites` rule with `"source": "**"` and `"destination": "/index.html"`; `firebase init` writes it when you say the site is a single-page app. Hosting answers in a fixed order: reserved `/__/*` paths, `redirects`, exact-match static files, `rewrites`, your `404.html`, the default 404. So real assets still win, and the rewrite only fires when no file exists; it returns `index.html`'s content at the original URL, with no redirect. Within `rewrites` the first matching rule wins, so a `/api/**` rule pointing at a function must come before `**`. The catch-all also means `404.html` is never served, and a stale tab asking for a JavaScript chunk the last deploy removed gets `index.html` back, which the browser then fails to run. Exclude asset paths, as in the docs' `!/@(js|css)/**` example, and render a not-found view in the app.

code

json · 10 lines
json
{
  "hosting": {
    "public": "dist",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "rewrites": [
      { "source": "/api/**", "function": { "functionId": "api", "region": "europe-west1" } },
      { "source": "!/@(js|css)/**", "destination": "/index.html" }
    ]
  }
}

go deeper

for a junior

Recall that a rewrite serves another file's content without changing the URL, and that the SPA fallback is source ** to /index.html.

for a middle

Walk through Hosting's priority order and explain why real files still win, why first-match ordering puts function rewrites before the catch-all, and why 404.html goes dead.

for a senior

Diagnose the production symptoms: HTML returned for a missing chunk after a deploy, API calls answered by the shell, and crawlers seeing soft 404s; fix them with exclusions and ordering.

for a principal

Decide what a team standardises for every Hosting site: one reviewed rewrite order, asset directories outside the fallback, and an emulator check in the pipeline before a deploy.

## The problem Hosting has to solve A **single-page app (SPA)** ships one HTML file, `index.html`, and a client-side router draws each screen. Firebase Hosting serves static files from the deploy's `public` directory, so a request for `/recipes/42` looks for a file at that path. There is none, and without extra configuration Hosting answers with a 404. Why a reload hits the server at all is a browser-routing topic; here the question is what Hosting does with the request. The fix is a **rewrite**: a rule in the `hosting.rewrites` array of `firebase.json` that tells Hosting to answer a matching path with the content of another file. ```json { "hosting": { "public": "dist", "rewrites": [ { "source": "/api/**", "function": { "functionId": "api", "region": "europe-west1" } }, { "source": "**", "destination": "/index.html" } ] } } ``` When `firebase init hosting` asks whether to configure a single-page app and you answer yes, it writes the `**` rule for you. ## Hosting's priority order The rule is safe only because Hosting never reaches it for paths that have a real file. When several options could answer, Hosting decides in this order: 1. Reserved namespaces that begin with `/__/`. 2. Configured `redirects`. 3. Exact-match static content. 4. Configured `rewrites`. 5. The custom `404.html` page. 6. The default 404 page. So `/main.4f2a.js` is served as a file, and only paths with no file fall through to the rewrite. The docs state it from the rule's side as well: a rewrite applies only if no file or directory exists at the matching path. ## Order inside the rewrites array Within `rewrites` (and within `redirects`), Hosting applies the **first** rule whose `source` glob or `regex` matches. There is no "most specific wins". - A function or Cloud Run rewrite for `/api/**` must be listed before `**`, or the catch-all answers API calls with HTML. - A rewrite to a function forwards the full original path and query string, so the handler must expect `/api/recipes?page=2`, not `/recipes?page=2`. - `source` takes globs with extglob syntax; `regex` takes an RE2 expression. A rule has one or the other. - `redirects` still beat `rewrites` regardless of position, because they sit higher in the priority order. ## Rewrite versus redirect | | `rewrites` | `redirects` | |---|---|---| | What the browser sees | the destination file's content at the original URL | a 301 or 302 telling it to request the destination | | Address bar | unchanged | shows the destination | | `destination` | a local file that must exist (or a `function` or `run` target) | any relative or absolute URL | | Applies when a file exists at the path? | no, static content wins | yes, redirects are checked before static content | The SPA fallback must be a rewrite: a redirect to `/index.html` would replace the deep link in the address bar and the router would lose the route. Two other `hosting` keys also answer with redirects: with `"cleanUrls": true`, a request for `/about.html` gets a 301 to `/about`, and `trailingSlash` set to `true` or `false` redirects to add or remove the slash on static content; `trailingSlash` does not affect rewrites to Cloud Functions or Cloud Run. ## What a careless catch-all breaks - **The 404 page.** With `**` matching everything, step 5 is never reached, so `404.html` is dead. The app must render its own not-found screen for unknown routes, and crawlers see a normal page instead of a 404 status. - **Missing assets.** After a deploy that renamed hashed bundles, an open tab may request the old chunk. No file exists, the catch-all matches, and the browser receives `index.html` where it expected JavaScript, failing with a syntax or MIME-type error rather than a clean 404. The docs show an exclusion rule, `"source": "!/@(js|css)/**"`, that keeps asset directories out of the fallback. - **Later rules.** Any rewrite placed after `**` is unreachable. - **Re-running init.** Running `firebase init` again and choosing Hosting resets the `hosting` section to the default, which can silently drop hand-written rules. ## A checklist for the companion web app 1. Keep hashed assets under one directory and exclude it from the fallback. 2. List function and Cloud Run rewrites first, catch-all last. 3. Render a client-side not-found view, since `404.html` will not appear. 4. Test with `firebase emulators:start` before deploying, so the rule order is exercised locally.

  • Your fallback rule is listed before a rewrite of /api/** to a function. What happens to API calls?
    Hosting applies the first rewrite whose pattern matches, and `**` matches `/api/recipes`, so the API call receives `index.html` and the function never runs. The client sees HTML where it expected JSON. Moving the function rule above the catch-all fixes it; redirects are unaffected, because Hosting checks them before any rewrite.
  • Why does a user on a stale tab see a blank page after you deploy a new build of the SPA?
    The old page requests a hashed bundle that the new deploy no longer contains. With a `**` fallback, Hosting finds no file, applies the rewrite and returns `index.html`, so the browser fails to execute HTML as script. Excluding asset paths from the fallback turns this into a plain 404 that the app can detect and answer with a reload.

  • The fallback should be a redirect that sends the browser to /index.html
  • A catch-all rewrite overrides real files such as /main.js
  • Order inside rewrites does not matter; the most specific rule wins
  • With a catch-all rewrite, Hosting still serves 404.html for unknown paths
  • Rewrites take precedence over redirects in firebase.json