Setting Environment Variables In Nodejs With cmd-env

I just came across environment variables while learning Nodejs and thought I’d share some quick insights with you. It’s very basic, but I hope it helps

Nodejs has a global object called process running when it boots/runs. On this object you can find a property, which is another object, called env. This object holds all the environment variables in your Nodejs environment. You can check all the currently available environment variables by running:

console.log(process.env)

The cool thing about env object is that you can set/modify values as you like. This means you can create your own variable for let’s say, a database connection url:

process.env.DATABASE_URL = "a database url"
console.log(process.env.DATABASE_URL)

Output:

a database url

By convention you name your environment variables in uppercase and split the words with an underdash.

The value for the environment variable is only set during the Nodejs execution, meaning that it is set when Nodejs process is running. Once the process is stopped the variable disappears.

Instead of having environment variables set in different files of your application it’s a good idea to keep them in one file. Let’s say you have a database url, a Json Webtoken and a server portnumber. These are all in different files of your application. We want to convert them to environment variables and have them gathered in one place. We do that by creating a .env file, which we will call “environment-vars” in this case:

// config/environment-vars.env

DATABASE_URL = "www.mysite.com/dbconnection"
JSON_SECRET = "asecret"
PORT = 3100

Great! Now the they can be used in other parts of your application.

// src/database-config.js

dbConnection = process.env.DATABASE_URL

A little side note here is that setting environment can be tricky, because each OS (Windows, Linux etc.) does it in its own way. To solve this problem you can use the npm package env-cmd. Install it as a dev dependency with

npm i env-cmd --save-dev

After the installation completes go to your package.json and add the filepath for your environment variables to the script you use to start your Nodejs application.

env-cmd -f ./config/dev.env

In this example it would look something like this:

"scripts": {
   "start": env-cmd -f ./config/dev.env node index.js
}

There! Nothing has changed as such, but now if you should run this on another OS it will work just the same as the one you are currently using 😀

I’ll end this post by saying that the .env file usually goes into your .gitignore.

Resources