Adding an .env file to React Project

4 steps

  1. npm install dotenv --save
  2. Next add the following line to your app.require('dotenv').config()
  3. Then create a .env file at the root directory of your application and add the variables to it.
// contents of .env 

REACT_APP_API_KEY = 'my-secret-api-key'
  1. Finally, add .env to your .gitignore file so that Git ignores it and it never ends up on GitHub.

If you are using create-react-app then you only need step 3 and 4 but keep in mind variable needs to start with REACT_APP_ for it to work.

Reference: https://create-react-app.dev/docs/adding-custom-environment-variables/

NOTE – Need to restart application after adding variable in .env file.

Reference – https://medium.com/@thejasonfile/using-dotenv-package-to-create-environment-variables-33da4ac4ea8f

Leave a Comment