When creating a react project you may have some variables you wouldn't want to expose and commit to github. You perhaps have used an environment variables. Excellent job! That's good practise.
However, Because react apps create static client side JS, HTML and CSS files the environment variables such as REACT_APP_SECRET_API_KEY
will be process.env.REACT_APP_SECRET_API_KEY
in your hosted repository but in the actual running app anyone can view the source code and find the API key. Uh-oh. Disaster. Check now if you want. Go to your site and if you are in chrome open dev tools, go to the sources tab and search for your env variable in a JS file. You may find that you are exposing those secrets.
Please remain calm. There is a solution. I felt the same when I became aware of this.
When you added REACT_APP
at the beginning you were "protecting" yourself from accidently revealing other secrets on the server if you set a similar named environment variable. Well that worked...
So what is the solution?
Don't store secrets in your react app. That's probably a first rule. If you store any API keys, access keys or anything like that, please be careful when storing in you react app because all the code is exposed client side.
React is simply a HTML file running a big JS file with all your js code in. You can also set GENERATE_SOURCEMAP=false
which will hide your source code but I want you to be extra safe.
But how could you do it safely?
You can store the keys on the server side. Which means you'll have to create a small express server which can use process.env
and then in your react code you can call an API which is on your server rather than using and exposing an API key. The youtube channel 'Code with Ania Kubów' does an excellent job at explaining how to do this (see the notes at the bottom)
By doing it this way any API calls can be to your local server at mywebsite.com/api/endpoint
. This endpoint can then call your actual api endpoint with the API key and any other secrets appended on the end or included in the body. This request will be hidden as it's on the backend rather than running in the client.
Thank you so much for reading this article. If you have any comments or feedback please leave a comment or like this article. It means a lot. Thank you.
That's all folks.
Top comments (4)
Good tip for using a proxy backend to route your requests. You can achieve the same thing using nginx, nextjs… 😊
Thanks, I didn't know that
This reminds of me the time when I used to store my secrets as a string labelled "secretKey" since I was unaware that this key was supposed to be used as a private key for the backend to authenticate incoming requests received from a client. This post definitely helps those learning to use API keys (and JSON webtokens) for the first time to avoid those silly mistakes I made :¬)
Thank you for the encouragement.
It certainly is common. I thought using just Env variables was good enough. But not with client side react apps.