Node Environment

Configuring Node Environment

Node Environment

by John Vincent

Posted on July 1, 2017

There are many ways of doing this. Let's discuss.


  • Code is checked into a remote repository. It cannot contain any information that should be private, for example
* keys, hashes, database info, users, passwords, email configuration etc.
  • Applications frequently have variables that are unique and configurable for each environment.

Node Environment

Node uses process.env

For example, environment variable john would be



Node supports global variables. Be careful if using multiple instances.

To make a variable global, just precede the variable name with a global. or GLOBAL.

For example

global.DATABASE_URL = 'mydb';

global.logger = new logger(customConfig);


dotenv is a npm package.

npm install dotenv --save

Place at start of config.js


This package loads variables from root/.env and makes them accessible as


Thus, create file root/.env and save variables


Do not add .env file to a repository, add the following to .gitignore



Configuration data needs to be set at the start of the app, thus server.js for example

const {PORT, DATABASE_URL} = require('./config/config');

config.js, for example


exports.DEVELOPMENT = process.env.DEV;

exports.AUTHENTICATION_KEY = process.env.KEY;

exports.DATABASE_URL = process.env.DATABASE_URL ||
                       global.DATABASE_URL ||
exports.TEST_DATABASE_URL = (process.env.TEST_DATABASE_URL || 'mongodb://localhost/mydb-test');

exports.PORT = process.env.PORT || 8080;                  

Environment Variables for a Service

Environment variables that pertain to a service, rather than an application, I prefer to store in the Unix environment by setting them in the profile. An example is the email service.

Unique to Application

These environment variables I prefer to configure in config.js

exports.COOKIE_NAME = 'app-cookie-name';

Unique to Environment

These environment variables I prefer to configure in .env with an override if appropriate.




exports.DEVELOPMENT = process.env.DEV;
exports.DATABASE_URL = process.env.DATABASE_URL ||
                       global.DATABASE_URL ||


Environment variables can be configured prior to running an application. For example

"scripts": {
"start": "nodemon server.js",
"test": "MY_KEY=value mocha --recursive ./test"


Heroku loads .env files into the environment prior to running the application.

Note that this does not apply to mocha unit tests. You must load environment variables required by mocha tests as shown above.