Search code examples
firebasegoogle-cloud-functionsfirebase-hostingfirebase-cli

Hosting rewrite with custom domain for function doesn't work


I am trying to setup firebase with a domain so that:

  • My functions are available on mydomain.com/api/functionName
  • My hosting is available on mydomain.com (or preferably mydomain.com/client/, but the other will work as well)

My firebase.json looks like this:

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

After deploying this and accessing the domain in the browser, both / and /api/helloWorld routes will always take my to my client app, not to my function.

What's really weird to me is that when running the emulator locally, hosting does not work at all but localhost:5000/api/helloWorld works as expected and calls the function.

enter image description here

What am I doing wrong here? It feels as if my firebase.json is not deployed at all.

Update

Here's my function definition if that has anything to do with it:

exports.helloWorld = functions
  .region("europe-west3")
  .https.onRequest((_, response) => {
    response.send("Hello from Firebase!");
  });

Solution

  • Rewrites work in a "first match wins" order. Since you have a ** at the top, it will match all URLs and the second rewrite is never accessed. If you switch the order, you should see it work as expected:

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