Search:   Dictionary All Posts
Store Your Knowledge at the Brain Bank!

Setup Private Environmental Variables - process.env

By Jamie in Lessons / Programming - JS  2.17.19  (Source)
Summary - We use a package called dotenv to protect variables like username, passwords and api keys on the backend in express, and also on the frontend with React to save things that might be repeated like the website URL in api calls.
Setting up dotenv in the backend in express is done differently than in frontend with React. React already comes with it, but the .env file must name variables differently.

dotenv in Express
npm install dotenv

create a .env file in the top most directory

on the main server page

in the .env file create variables like this...

then on any page you want to use those variable you must require the dotenv config file


and call each by using process.env.variableName
host: process.env.DB_HOST,
user: process.env.DB_USER
pass: process.env.DB_PASS

dotenv in React

dotenv is bootstrapped with create-react-app so no need to install it on the frontend. However you still need to create the .env file in the highest directory of the project.

The big difference in using it in React vs Express is how you name the variables. It is required to name all variables in the .env file with the prefix of REACT_APP_

This is to avoid variable name collisions.

Also, you do not need to require the config file on any pages, you can simply use the environmental variables wherever you want.

Keep API keys, or the domain name in this file. This way when you switch to production server all you have to do is change this one variable.