Environment variables are variables that can contain sensitive date in your project. They are variables you wouldn’t want to share with users of your codebase, like api keys, database url, etc. The environment variables also allow applications to behave differently depending on the environment in which the application runs. The environment here could mean your computer, a cloud server, a container, etc.
process.env
The process.env
is a global object that is used to access all the environment variables of the environment your application is running. This means that it is accessible everywhere in our application.
process.env
In the example below, we accessed the process.env
object by logging it into the console. Now we can list the default environment variables of our application.
console.log(process.env)
You can set up your environment variables directly in any application file since the process.env
is a global object. See an example below:
// Set an environment variableprocess.env.AUTHOR_NAME="Theodore";// Read the variable that was setconsole.log(process.env.AUTHOR_NAME);
It might not be the best approach to create your environment variables anywhere in your application. It is better to create the .env
file and read the environment variables with dotenv
npm package.
We want to make sure that we set up our environment variables the proper way and that we are able to read them.
.env
file and create the following environment variables:NAME = Theodore
PLATFORM = Edpresso
dotenv
package and require it in your node starter file, which could be index.js
, server.js
, app.js
or whatever you choose to call it.require("dotenv").config()
Now that we have required the dotenv
package in our project starter file, we can access our custom environment variables.
See an example below:
require('dotenv').config();console.log(process.env.NAME); // logs Theodoreconsole.log(process.env.PLATFORM); // logs Edpresso
In the code above, we created our custom environment variables in a .env
file and used the dotenv
package to be able to read them directly in our index.js
file. Now we can list our custom environment variables.