Environment Variables
#
WhyWhen we use sensitive information (such as API keys, database configuration and variables, etc) in our projects, we want to protect that information from outside eyes. We definitely do not want to push up sensitive information to GitHub, even though we will utilize remote repositories for storing copies of our projects.
We can use “environment variables” to pass sensitive information throughout our project, without exposing their values. It also allows us to easily update configuration variables in one place.
#
WhatAn environment variable is a variable whose value is set outside the program, through functionality built into the operating system. An environment variable is made up of name/value pairs, and any number may be created and available for reference throughout your project.
#
How#
Server SideWe specify environment variables in a .env
file. During application initialization, the environment variables are loaded into process.env. From there, we can access the variables with process.env.VARIABLE_NAME
.
Before we get started, we’ll use an npm package, dotenv
, in our projects. Install that now.
Now, create a subfolder in your “src/server” folder named config
, and add a new file, index.ts
, that will be our default export.
Now inside our “src/index.ts” file, import dotenv
. Next, we’ll add a conditional that checks if a .env file exists in our project, and throws an error if such a file doesn’t exist.
Then export your needed configuration variables:
Now we can import our config
file in any server file where we will use these values.
For example, we could use the variables defined in our .env file and exported through our config/index.ts to create our mysql connection:
#
Client Side (React)Since client side code is completely visible to the user, you won't be able to store secret values as environment variables, but you can still set them up to be read from a .env as more or less configuration values.
In react, name all of your environment variables starting with REACT_APP_
in your .env
files like the following:
#
Wrapping UpMake sure to add .env
to your .gitignore
file so that you don’t push secret information to Github.
When you host your application for production, you’ll need to set the same environment variable names with their production values through the hosting service, and you’ll be all set!
#
Takeaways- Environment variables are variables with values that are set outside the program, through functionality built into the operating system
- Environment variables are made up of name/value pairs
- Always include your
.env
file in the.gitignore
file if it contains secret values