Keeping API key hidden using react

Hey all,

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]"

Now here is an example fetch to the api;


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?

Option 2: Don’t let the client side touch the API key:

1 Like

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 ?

1 Like

Yes, your react app can send an ajax request to the endpoint that you set up and your server can call the API


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.


But then cant people have access to the dotenv file? Or have access to the server file?

Another question: dotenv file will be added into build. How to separate them from build but still have the user to access to it

Welcome starchcode.

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, and only provides data based on routes (eg /learn)

So, here is a simplified case:

function getDataFromServer() {
  const data = fetch('');
  // Use the data returned on the client side


const SECRET_KEY = process.env.SECRET_KEY;
app.route('/learn').get((req, res) => {
  database.find(SECRET_KEY, (data) => {
    res.json({data: data});

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.

I hope this clarifies.