How to keep an API key secret in React?

I want to deploy a React app (as a static site using just react/html/css) on render which uses an API key that must stay confidential. From lots of blog reading, I understand that this must not be stored on github. However, whether I stored the API key through either the Environment Variables settings or in a .env file in the Secret Files settings of the render dashboard, the API key (rather than the variable name) was displayed on the console when there was an error with my fetch request.

(The working code) in my app.js file

  React.useEffect(() => {

      fetch(`https://api.timezonedb.com/v2.1/get-time-zone?key=${process.env.REACT_APP_API_KEY}&format=json&by=zone&zone=Australia/Brisbane`)
      .then(res => res.json())
      .then(data => setBrisData(data.gmtOffset) )
      .catch(err => console.log( `This is the error: ${err}`))

  }, [])

The console log when it didn’t work (note: fake API key below):

Blocked loading mixed active content “http://api.timezonedb.com/v2.1/get-time-zone?key=4E4E4E4E4E4E&format=json&by=zone&zone=Australia/Brisbane”

Thus:

a) do I just need to avoid errors in order to keep the API key confidential (seems a bit dicey to me, but I’m new to all this)

b) is it actually appropriate to be using the Environment Variables / Secret Files settings on render to keep an API key confidential?

c) if not, what should I be doing?

Thanks in advance for your advice

Hello,
To my knowledge, there isn’t absolutely safe to store API key/secret in the frontend/React.
Here are some discussions:

I would suggest storing API key in the backend web service.

1 Like

Thanks very much for your reply. Not sure how I missed those answers on stackoverflow but they are clearly what I needed. Have a great day.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.