I have a firebase project.
I am calling an external api via cloud function in the hope the api key (stored in env variable) will be less discoverable.
While I have managed to get the following code working in the emulator, it doesn't work after deployment.
const {onRequest} = require("firebase-functions/v2/https");
const fetch = require("node-fetch");
const makeRequest = async (req, res) => {
const apiKey = process.env.KEY1;
const apiUrl = `[externalAPIurl]&key=${apiKey}`;
try {
const response = await fetch(apiUrl);
const data = await response.json();
res.set("Content-Type", "application/json");
res.status(200).send(JSON.stringify(data));
} catch (error) {
console.error("Error:", error);
res.status(500).send("Internal Server Error");
}
};
exports.helloWorld = onRequest(makeRequest);
CORS is flagged as the problem. Postman tells me that it's a lack of authentication being passed in the header (error 403).
I have struggled to adapt existing code (Google samples/turtorials, and community-provided excerpts). For example:
- The following excludes req, res parameters and isn't obviously amenable to calling an external api (url) https://cloud.google.com/functions/docs/samples/functions-bearer-token?hl=en
- The following documents how one might create authenticated functions: How to invoke "authenticated" functions on GCP cloud functions But the linked documentation suggests the approach is for development purposes (only?): https://cloud.google.com/functions/docs/securing/authenticating
- This is very close, but is 1st gen and lacks the external api call: https://github.com/firebase/functions-samples/blob/main/Node-1st-gen/authorized-https-endpoint/functions/index.js
For context, the plan is to anonymously authenticate all users of the website. If anyone can point me in the right direction, that would be sweet.