I’ve got an API key that I’m obviously meant to keep private, that I want to use in a react app.
I’ve stored it as an environment variable in the react app by creating a .env file and adding REACT_APP_APIKEY="[my api key]"
I don’t have to write my apikey explicitly in the code here, so i can upload everything except the .env file to github and the apikey will still be private, but if I put a demo up that actually uses this code, you will be able to go to the network tab in chrome and see my api key whenever you make a request. I could host my own node.js api, which I send the fetch request to then forward the fetch to the actual api and inject the apikey there, but that seems like a pretty complicated solution. Any other ideas? or should I just not worry about it?
Okay, I’m pretty sure I get it. Just to clarify, in order to build a simple weather app that uses an API key, I will also need to write a backend, just because of the use of an API key ?
Yeah, security can be annoying, but as you have said through your very question, you recognize that secrets must be kept between trusted parties, and the client isn’t one.
This post is over a year old. So, I am going to close it. I recommend you open your own topic to ask any questions you have, if this does not help:
Provided people do not have access to the server files, they will not have access to the .env file. A secure server only provides access from a specific domain (eg freecodecamp.org), and only provides data based on routes (eg /learn)
So, here is a simplified case:
CLIENT
function getDataFromServer() {
const data = fetch('www.freecodecamp.org/learn');
// Use the data returned on the client side
}
From the above, the just is the secret is never sent to the client, only the data is.
.env file will be added to the server build. Not bundled and sent with the clientside.
As mentioned above, it should not end up in the same bundle as the client side. However, most use cases of a .env file do not even allow it to be bundled, and the keys are added manually into the server configuration as environment variables.