Dewey
Dewey

Reputation: 1223

Retrieve the current unique URL of a firebase function

I am writing a firebase cloud function to authenticate user and obtains refresh_token and access_token for later use. Here is the snippet to initialize Google OAuth2 client:

const { google } = require("googleapis");

module.exports = () => new google.auth.OAuth2(
  GOOGLE_CLIENT_ID,
  GOOGLE_CLIENT_SECRET,
  `${BACKEND_URL}/authCallback`,
);

Currently I have to deploy the function to firebase first before I can get the value for BACKEND_URL. Is there away I can retrieve the current firebase unique URL inside the function?

Upvotes: 5

Views: 3115

Answers (2)

daniel-sc
daniel-sc

Reputation: 1307

For the NodeJS v10 runtime the following works for http functions:

export const yourFunction = functions.https.onRequest(((req, resp) => {
    const url = `https://${req.header('host')}/${process.env.FUNCTION_TARGET}${req.originalUrl}`;
    resp.send({url: url});
}))

You might skip req.originalUrl if you don't care about additionl path/query params.

Upvotes: 4

Doug Stevenson
Doug Stevenson

Reputation: 317372

HTTPS function urls look like this:

https://us-central1-YOUR-PROJECT.cloudfunctions.net/test

where "us-central1" is the region of deployment, and "YOUR-PROJECT" is the name of your Firebase/Cloud project. "test" is the name of the function. Everything else stays the same.

process.env.FUNCTION_REGION is the region where the current function has been deployed.

process.env.GCP_PROJECT is the name of the project where the current function has been deployed.

So, you can build the URL using the contents of those two process environment variables, if you are assuming that the currently running function shares the same project and deployment region as the target HTTPS function.

Upvotes: 6

Related Questions