How to Create an Environment Variable in a React App

,

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:

  1. Before starting, make sure you added .env to your .gitignore file.
  2. Open the root directory of your React app.
  3. Create a file named .env and open it
  4. 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
  5. Save this file and Restart your server if it’s already running.
  6. 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:


Leave a Reply

Your email address will not be published. Required fields are marked *