I'm trying to protect my API key using a Netlify function (a modified return-env.js) that grabs and outputs an environment variable. Since my project is in vanilla JS, I then have to grab the key from the function in order to use it. But this is where it gets difficult.
Currently I have:
function getKey() {
(async ()=> {
const response = await fetch('/.netlify/functions/return-env')
const resObj = await response.json()
console.log(resObj);
return resObj;
})();
}
console.log("my key " + getKey())
const Airtable = require('airtable');
const base = new Airtable({apiKey: 'EXAMPLE-API-KEY'})
getKey()
always returns undefined, as would resObj
if logged outside the function. What's missing here?
getKey will return undefined because you are not returning anything in the function call
function getKey() {
return (async ()=> {
...
})();
}
It will now return a promise which you can then chain or await, awaiting would require it to be in an asynchronous function.
if you just wanted to .then() off it:
getKey().then((key) => {
// do something with the key object
}