Firebase Functions domain

How to use a custom domain for Firebase Functions

Ready, Set, Fire!

Hi there, Tom here writing! If you're an avid user of Firebase, you know how simple handling your backend-less backend actually can be. Thanks to Firebase Functions, I just write my business logic as a plain function, deploy this very function via the CLI and can reach it from the cloud everywhere on the planet. The setup itself is so simple, that the deployment alone only takes a couple of minutes time at maximum. But there's a special case with Firebase Functions that might need some more work - using a custom domain, and not the one provided by Firebase.

The challenge

If you just deploy Firebase Functions as described, you'll get host under a subdomain from Google, specifically under

cloudfunctions.net

For simple use cases, this is mostly what you need - just deploy the thing and make it available to consume. But other use cases require your backend to be reachable under your domain. For this example, I'll use my own domain flaming.codes.

The setup

Here are the prerequisites, just to make sure:

  • you've setup a Firebase Project
  • under Hosting, you've set up your custom domain; this is a straightforward process, where you just have to store a TXT-record at your hosting provider

The config

To actually make your custom domain not only work for your hosted web app but your functions as well, firebase.json has to be updated (explanation after the sample):

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

The sole trick to make it work is to update the hosting key, not functions, in your firebase.json. What we're basically doing is telling Firebase that from our hosted web app, all calls to /api/... should be redirected to the function called api. The thing that took me the longest was the second item, where I explicitly have to declare every other route than api to be handled as a default web app route.

Using the following setup, the old cloud function

https://uscentral1-flaming-codes.cloudfunctions.net/api

therefore becomes

https://flaming.codes/api/...

Note that order is important here, the rewrite-rules get processed from first to last element, so in this case top to bottom, visually speaking. Using a wildcard to re-map all your functions is really not advised for general usage, as it would break your web app.

Wrap up

And yeah, it's really no magic but can help greatly when using Firebase Functions in certain use cases. We've seen how to rewrite your cloud functions as part of the already registered domain, therefore eliminating the requirement for a new, custom subdomain - although that's possible as well, but out of scope for this tutorial.

  • Tom