Create-React-App allows you to set environment variables. This is often used to store secret keys, for example, API Keys. You need those to authenticate a request to a third party service (i.e. a call to the Open Weather Map API).
Instead of using the key directly in your file, you store it in an
.env file and reference it. You don’t commit this
.env file to source control (Github, Gitlab, etc.).
At least, this is the answer to a popular Stackoverflow question: How do I hide API key in create-react-app?
But it doesn’t hide your secret keys!
You only have to read the official documentation for Create-React-App:
WARNING: Do not store any secrets (such as private API keys) in your React app!
Environment variables are embedded into the build, meaning anyone can view them by inspecting your app’s files.
So, what is the solution?
3. Is there a canonic way of using API keys in a react app? Or is it up to the individual developer?
Answer 3: The canonical way to use a third party API key is for your client side app to send a request to your backend API. Your backend API then formats the request as per the third-party API, adds the key and makes the call to the third-party API. Once it receives the response, it can either unpack it and translate it into domain objects which your front-end app would understand or send the raw response back to the front-end app. In this way, the API key stays at the backend and is never sent to the client-side.