A checklist to a working .env in React

A checklist to a working .env in React

Overview

The vital reason for setting environment variables is to protect the data/information that would be used on a project. There are other essential grounds for storing environment variables which include:

  • restricting access to that information,
  • restricting usage of the data,
  • easy reusability in different parts of a project.

You can easily add dotenv package to your react app and get it to work under the following conditions.

-> Create a file with the name .env, no extensions. Whichever file name you choose on your local, ensure it is added to your .gitignore. E.g

.env
.env.sample
.env.local
.env.development
.env.production

-> Ensure you add the file to the root directory. Meaning add your environment variable file to where files like package.json, package-lock.json, .gitignore, yarn.lock, etc.

-> The variable name must start with REACT_APP. You don't have to add quotes to the value of the key. E.g

REACT_APP_API_SECRET = whatTheValueIs

-> There is no need to add comma or semicolon after each variable. E.g

#DATABASE
REACT_APP_DB_NAME = dbname
REACT_APP_DB_HOST = dbhost
REACT_APP_DB_PASSWORD = dbpassword
REACT_APP_DB_USERNAME = dbusername

-> You can access the variable as such. You can choose to use it directly without setting it to a variable.

const apiSecret = process.env.REACT_APP_API_SECRET
or
const apiSecret = process.env["REACT_APP_API_SECRET"]

-> Once you make any changes to your .env, be sure to restart your local server so that the changes can reflect.

With all these, your react app will be good to run using environment variables.

Happy coding!