Search code examples
firebasegoogle-cloud-platformgoogle-cloud-functionsfirebase-hosting

How to use rewrite for base url with a declared public folder in firebase hosting?


I'm trying to configure a web app to use hosting for all static resources, such as jpegs, pngs, etc. But I want to route all requests to a cloud function to monitor traffic for various security reasons.

I managed to achieve this for all routes except the home route using this:

    "hosting": {
        "public": "public", //without this everything goes through function, with it the base url is treated like a static get for index.html
        "ignore": [
            "firebase.json",
            "**/.*",
            "**/node_modules/**"
        ],
        "rewrites": [
            {
                "source": "**",
                "function": "sendWebApp"
            }
        ]
    }

The problem I'm facing is with the home route/base url request. It's ignoring the rewrite for "myurl.com" but uses the rewrite for "myurl.com/whatever-I-type-here". How can I get it to route to the function for the base url as well?

(For clarity.) EDIT: How can I get firebase hosting not to treat the base url as a static request for index.html?


Solution

  • Firebase Hosting by default will always send index.html from the declared public folder when a request is made to the base URL. The only way to override this is to remove the index.html or don't include the "public" declaration in firebase.json's hosting configuration.

    Because static files ignore the rewrites configuration, you can simplify your rewrites to just:

    "hosting": {
      // ... other props ...
    
      // Serves the function for requests to files or directories that do not exist
      "rewrites": [ {
        "source": "**",
        "function": "sendWebApp"
      } ]
    }
    

    Importantly, if you are accessing a directory of your site, like / or /dashboard/, the index.html in those directories will be served if they exist. This means that your configured rewrite rules will never be checked in these cases.