Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect Firebase Hosting root to a Cloud Function is not working

I'm using Firebase Hosting with a firebase.json file that is supposed to forward all traffic to a cloud function (prerender) which populates meta and og tags for SEO.

{
  "hosting": {
      "public": "dist/prod",
      "rewrites": [
       {
          "source": "**",
          "function": "prerender"
       }
      ]
   }
}

My prerender function is is handling the request and rendering the HTML file. This works fine:

export const prerender = functions.https.onRequest((req, res) => {
   console.log('prerender function: "' + req.path + '"');
   ...
}

When hitting the end point at https://xxx.cloudfunctions.net/prerender, I correctly get the call in the Firebase Dashboard under Functions -> Logs:

prerender function: "null"

However, when calling https://mypage.firebaseapp.com, I get no logs and it seems to render the index.html inside of my dist/prod folder.

Is there anything I'm missing with the rewrites? I tried rewriting / to the same function, but no success. Any hints much appreciated!

like image 861
Andy Abgottspon Avatar asked Jul 02 '17 12:07

Andy Abgottspon


1 Answers

You should be able to route all URLs to a function in exactly the way you're showing. I'm guessing that you still have an index.html file located in your dist/prod directory. In my test project, I simply renamed the root index.html to something else, and requests to / were routed to my function.

It turns out that if there is static web content that matches the client request URL, that will be served instead of delegating to the function. This is true for any incoming URL. The only way to truly ensure that all requests are routed to your function is to remove all content from your dist/prod folder before deploying.

I believe the key piece of information is in the documentation for rewrites:

A rewrite rule is only applied if a file or folder does not exist at the specified source, and returns the actual content of the file at the destination instead of an HTTP redirect.

like image 179
Doug Stevenson Avatar answered Oct 25 '22 07:10

Doug Stevenson