Let's say you are using a fetch in React App to get info from an API, and are using your API key to connect to that API. The key is private, and should not be visible outside your code. How can you achieve that and keep your code functional?
These are my notes on what worked for me. It took me a while to figure it out, so I wanted to share it, as a personal note to self, and, hopefully, to help someone else with the same issue.
1- Write npm install dotenv in the Terminal (I am using the Terminal in VSC).
2-Create an .env file in the root folder of the project (this means, outside the src folder).
3-This .env file will have the environment variables that are to be kept hidden. Since I am using React App, these variables have to be preceded by REACT_APP_. In my case, my variable is called REACT_APP_API_KEY=numberOfYourAPIKey.
4-Go to the .gitignore file in the root folder, and make sure .env is added to the list of files that will not make it into GitHub.
5-Go to your App.js file, and on the top list of "imports," (before declaring the App function), declare a variable to call the config function. I wrote const dotenv = require('dotenv').config() (you can use the variable name of your choice).
6-Go to any component using this API key, and, inside that component js file, declare a variable that will contain the API Key from your .env file. I wrote const api_key = process.env.REACT_APP_API_KEY. This is the variable you will use in your fetch. For example, fetch(
The first "api_key" in the example is given by the API URL, the one inside the curly brackets is the name of my variable "api_key".
7-You can upload your project to GitHub now, and your API Key will not be visible.
8-In my case, I deployed my project to zeit.co (now vercel.com), by importing my GitHub project into this platform. Once imported, you will see three tabs in vercel.com: Overview, Deployment, Settings. Inside Settings, you will find the option to declare a variable under Environment Variables. There you should use the name of the variable you used in your .env file (REACT_APP_API_KEY), and copy-paste the actual value of the variable (your API Key) in the field box next to the variable name, where it says "VALUE (WILL BE ENCRYPTED)".
Your code should be working as if the actual API Key was still shown in your code, only now it will be hidden outside your local environment. Hope it helps!