If you’ve used Create React App, you can set up and use environment variables out of the box as you’ll have a NODE_ENV defined for you named REACT_APP_ which you can reference with process.env.REACT_APP_.
Otherwise, you’ll need to install the dotenv package via npmjs.com’s library and follow the documentation to define and configure your variable.
Once you have your React app setup and ready for your new variable:
- Before starting, make sure you added .env to your .gitignore file.
- Open the root directory of your React app.
- Create a file named
.envand open it - Inside that file, add a new variable that starts with
REACT_APP_and = it to your API Key e.g.REACT_APP_MY_API_KEY = 1a2b3c4d5e6f7g8h9i0 - Save this file and Restart your server if it’s already running.
- Now you can use your environment variable within your app i.e.
process.env.REACT_APP_MY_API_KEY
It’s important to note that these environment variables are used for development only and are embedded into the build, which means anyone can inspect the app’s files and see them on a live site at runtime.
Extra Resources:
- Adding Custom Environment Variables – Create React App
- dotenv – npmjs.com

Leave a Reply