Search code examples
node.jsfirebasefirebase-hostinggoogle-cloud-run

How to get hostname on a Cloud Run server from a request sent from a Firebase Hosting rewrite?


I need to do SSR on my web app. And since it's an international website, I need to know the domain (hostname) that is requesting the website so I can render in the appropriate language for the user.

Example:

https://www.mydomain.co.uk // WILL RENDER IN ENGLISH
https://www.mydomain.es    // WILL RENDER IN SPANISH

Here is the setup

  • An express server on a Cloud Run docker Node.js container
  • Firebase Hosting will rewrite all requests to the Cloud Run container

Here is how Firebase rewrites the traffic:

firebase.json

"rewrites": [
      {
        "source": "**",
        "run": {
          "serviceId": "my-server-id",
          "region": "us-central1"
        }
      }
    ]

It's working fine. But I've noticed that all requests reach my Cloud Run server with the following hostname:

  • req.hostname === "https://my-server-id-on-cloud-run.run.app", which is default Cloud Run url for my server service.

I've noticed that Firebase Hosting adds my actual domain name to the following header:

  • x-forwarded-host: "https://www.mydomain.co.uk" OR "https://www.mydomain.es

Is this the correct header to read my domain from? I didn't find any documentation on this subject.

If a user hits my website either using my app's Firebase default urls (web.app OR firebaseapp.com) or through a connected custom domain, I can count on the fact that the x-forwarded-host header will always be there, correct?

Could there be a situation where x-forwarded-host would contain more than one URL? Like it happens in the x-forwarded-for with IPs?

References:


PS: I've noticed that if I hit my cloud run server directly from the Cloud Run default url .run.app, the x-forwarded-for header is not present, which makes sense, given the fact that it is a direct request, and not a rewritten one.


Solution

  • According to this doc,

    1. This header could be the best option, given all the pros you share plus:
    • X-Forwarded-Host header is useful to determine which Host was originally used.
    • This header is used for debugging, statistics, and generating location-dependent content.
    1. The Syntax is: X-Forwarded-Host: <host>, and the Directive is:
    <host>
    The domain name of the forwarded server.
    

    This means that you can't have moew than 1 value in that header.