Knowing the current public hostname of a Netlify function

Hello everyone,

tl;dr;
Is it possible, from inside a lambda handler, to know the public hostname this function is accessed from?

For example, if I have a function on http://foo.netlify.com/.netlify/functions/debug, how can I know, from inside this function handler, that it’s running on foo.netlify.com?

What I want to build:
My goal is to have one website available through multiple domain names. I added a redirect to my website so all incoming request to the root actually go through my lambda. Based on which domain is currently targeted, I want to return slightly different content.

What I tried
During development, I was using netlify-lambda to locally serve my functions. In that context, I could read event.headers.host and correctly get localhost:9000 so I assumed this was the way to go.

But once I deployed in production, I realized the headers exposed are totally different and do not include any mention of the public hostname.

Other workaround I thought of
I thought that maybe I could redirect each domain to a different subdirectory and then add redirect rules for each of this subdirectories to pass and additional header mirroring the domain name.

Something like www.foo1.com goes to foo.netlify.com/foo1 and www.foo2.com goes to foo.netlify.com/foo2 and then I add redirects such as /foo1 goes to my lambda with X-hostname: www.foo1.com as an additional header.

But I couldn’t find a way to have domains target anything else than the root, so I’m also blocked here.

Any idea, even an convoluted one, how I could have my lambdas aware of the url they’re running on?

Hi, @pixelastic, thank you for your patience.

It might help to clarify something before we go further. Are the function calls themselves happening because of a Netlify redirect? Or is site javascript making the calls to the functions? It sounds like the former is the case but I wanted to be sure.

Oh, that’s an interesting point, I forgot about that part.

The functions is happening because of a redirect, namely:

[[redirects]]
  from = "/"
  to = "/.netlify/functions/index"
  status = 200
  force = true

So a visit to the root of the project does actually land on the lambda, and that’s where I’d like to read the hostname.

Thanks for your time,

So the hostname of the lambda function is available inside the context object. Here’s an example of how to do it: https://github.com/depadiernos/deploy-id-test/blob/master/functions/getdeploy/getdeploy.js#L3-L7

function extractNetlifySiteFromContext(context) {
  data = context.clientContext.custom.netlify
  decoded = JSON.parse(Buffer.from(data, "base64").toString("utf-8"))
  return decoded
}

Let me know if that helps.