Adding Environment Variables in .env of your React App
Working as a developer sometimes require working with api and api keys. As a React developer how do you hide whatever api key you are working with without exposing it to the public on your Github or anywhere else it can be exposed?
The React team have seen the importance of using an environment variables, and they have included this feature in react-scripts@0.5.0 and higher. Setting it up and using it in your app might be easier than you think. I’m talking about less than 1min procedure and you are done with it, moving on to whatever you were doing. Why don’t get started on how to use this out of the box feature from react.
How To Get It Working

Step 1 — After creating your react app, make sure the react-scripts that was installed is 0.5.0 and higher. You can locate this in your package.json.
Step 2 — Create your .env file at the root of your app folder. If you place your .env file in the src or public folder, react won’t know it’s there. So just place it at the root folder of your app.

Step 3 — Create your variable appending REACT_APP_ at the beginning of any variable you will have in your file.
Example: REACT_APP_API_KEY or REACT_APP_SECRET

Why do you need REACT_APP_ at the beginning of your variable before anything else you want?
Because if you go ahead and ignore that, react will ignore your variable name to avoid exposing a private key on your machine that might have the same name. It can be painful and verbose adding REACT_APP_ to every variable you want to create in your .env file, but that’s how to tell react what to do to avoid exposing sensitive informations.
Step 4 — You can access your key anywhere in your app by assigning process.env.REACT_APP_SECRET_KEY to a constant or using it directly


And that’s how it’s done. Easy to use straight out of the box without needing any extra package. And please, don’t display anything from your .env file like that for the world to see.
If you are having trouble with your environment variable, make sure you using it properly by appending REACT_APP_ at the beginning of your variable.
Ensure your .env file is at the root of your app folder, and you are accessing it the right way with process.env.REACT_APP_whatever here.
Also, if your app was running when you created the file and variable, you might need to restart your app from your command line, with control + c and npm start or yarn start. That should do the trick.
Happy developing!
