Environment variables using Node.js

Some times you’ll need to use environment variables in your project. Node.js is able to parse
environment variables so let’s learn how to do it.

What is an environment variable?

An environment variable is a name associated with a character string. Depending on the variable, its utility may be different. Some are useful for not having to write many options when running a program, others are used by the shell itself (PATH, PS1,…)

1
2
export MYVAR="hello"
echo $MYVAR # hello

Example #1

We want to set the web server port of our project, due to we don’t know which port is free until the client install the project, so we need to leave the client to set the desired port. Also we set the number 3000 if no enviroment variable is found.

1
const port = process.env.MYPORT || 3000;

Example #2

We can use environment variables to set the database credentials, so we can have a configuration file that accepts environment variables as follow:

1
2
3
4
const config = {
db : process.env.DB || 'mongodb://localhost/foo',
password: process.env.DB_PASSWORD || 'somepass'
}

Example #3

Now take a look the next example. Defining a static JSON file, where we have keys depending on an environment variable:

1
2
3
4
5
6
7
8
9
10
{
"development": {
"SERVERURL": "http://localhost:3000/",
"PORT": 3000
},
"production": {
"SERVERURL": "https://yourdomain.com/",
"PORT": 5000
}
}

Using the global NODE_ENV environment variable, we can do the following trick:

1
2
const myEnv       = require('./my-env.json');
const myVariables = myEnv[process.env.NODE_ENV || 'development'];

References