Search code examples
firebasegoogle-cloud-functionssingle-page-applicationfirebase-hosting

Firebase Functions Custom Domain with Single Page App


I have a Firebase hosted single page app.

I also have 3 Firebase functions (contact, plans, features) that the app and external sources make requests of.

My app has a custom domain, which I'd like to access my functions via.

This is my current firebase.json config

{
  "hosting": {
    "public": "www",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

So currently all traffic goes to my app and routing is handled via my SPA. Access to my functions currently has to be done via the cloudfunctions.net URL which isn't ideal.

How can I add URL rewrite entries to this config so that my functions are accessible via my custom domain and my single page app handles the rest of the routes?

I have tried the following for the features endpoint:

"rewrites": [
  {
    "source": "/features/**",
    "function": "features"
  },
  {
    "source": "!/features/**",
    "destination": "/index.html"
  }
]

Where in my functions index.js I have:

...
exports.plans = functions.https.onRequest(plansApi);
exports.features = functions.https.onRequest(featuresApi);
exports.contact = functions.https.onRequest(contactApi);

But I receive 404 Cannot GET /features/123 as the response?


Solution

  • A few things:

    1. Make sure that your featuresApi handler is matching for the full URL path (e.g. /features/123 not /123). Firebase Hosting forwards the full path to the function, not just the ** part.
    2. Rewrites are resolved in order, so there's no need to do !/features/** for your second rewrite source. ** should be fine since if it matches /features/** it will already match the first rewrite and resolve to the function.

    Based on the error message, it seems likely that (1) is the culprit here.