API-Key exposed in Netlify even though set up as an environment variable

Hello

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.

Exposed Key:

The full code is available at GitHub - AlonCohen96/spring-rain: A real-time stockmarket research and overview React app

I followed this and this tutorial but the solutions are not working for me. No matter what I try the API-Key gets exposed.

Would greatly appreciate help, as I am at my ends witts.

My environment variables setup:

My serverless function in getApiKey.js:
image

How I access the serverless function in App.js:
image

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?

This is nothing to do with being on a free plan.

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:

let myData
fetch('https://yh-finance.p.rapidapi.com/stock/v2/get-summary?symbol=MSFT&region=US', options)
    .then(response => response.json())
    .then(data => myData = data)

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.

import axios from 'axios'
export async function handler() {
  return axios({
    headers: {
      'X-RapidAPI-Host': 'yh-finance.p.rapidapi.com'
      'X-RapidAPI-Key': process.env.API_KEY
    },
    params: {
      region: 'US',
      symbol: 'MSFT'
    },
    url: 'https://yh-finance.p.rapidapi.com/stock/v2/get-summary'
  }).then(axiosResponse => {
    return {
      body: JSON.stringify(axiosResponse.data),
      headers: {
        'content-type': 'application/json'
      },
      statusCode: 200
    }
  })
}

Make sure to add the following to your netlify.toml:

[functions]
  node_bundler = "esbuild"

thank you, i eventually came to a similar solution as yours:

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) {

    const { ticker } = event.queryStringParameters;

    let response = await fetch(`https://yh-finance.p.rapidapi.com/stock/v2/get-summary?symbol=${ticker}&region=US`, options)
    let stockSummary = await response.json();

    return {
        statusCode: 200,
        body: JSON.stringify({
            stockSummary: stockSummary
        })
    }
}
1 Like

Awesome! thanks for sharing your solution @Alon