I’ve been crunching unsuccessfully on this problem for 2 days. I developed a small app in React that does fetch-requests to the yahoo finance API. For this I use an API Key, that I’ve removed from from my Frontend code entirely and stored in my .env file which I then added to .gitignore. I then set up a serverless function and added the API Key as an environment variable as I deployed the app to Netlify. The app is working, the fetch calls are working correctly using the API-Key, BUT they are visible in the network tab, thus not hidden at all.
I am on the free plan for this API but still it shouldn’t be out there obviously.
Because this is how tools like React work. The environment variables are injected into the code during build.
The getApiKey.js you have provided a screenshot of (note: code in text form is much better than screenshots of code when you are asking for assistance) is simply returning the API to wherever it was called from. Instead it should make the call to the API endpoint utilising this key and return the data to the front end.
See [Support Guide] How do I keep my API keys/tokens safe using Netlify Functions?
Thanks a lot for your answer and looking through my problem. What you are saying makes sense, indeed the API call itself has to occur in the backend. I’ve tried to implement your solution, but I haven’t succeeded, I am not sure how to implement a fetch call inside of the AWS lambda function. Do you have any idea how to go about this?
my new getApiKey.js:
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': process.env.API_KEY,
'X-RapidAPI-Host': 'yh-finance.p.rapidapi.com'
}
}
exports.handler = async function (event, context) {
// implement fetch call to API here I assume, but how?
return {
statusCode: 200,
body: JSON.stringify({
data: myData
}),
}
}
And this is how I normally do a fetch call in the front-end:
Simply inserting that call into the exports.handler function obviously isn’t working, I’ve tried some variations with async/await but none of them succefully retrieve the data.
If anyone knows how to do this, your help would be greatly appreciated.