When you develop an application with Express or another framework, you will need to setup differents environments like production and develop.

Before running our app we can simply set the environment variable to production:

$ export NODE_ENV=production

on windows

$ SET NODE_ENV=production

A better way is to set it inside our package.json:

"scripts" : {
  "prod" : "NODE_ENV=production node index.js"
}

We now have access to that variable inside our app. index.js:

console.log(process.env.NODE_ENV) // production

Multiple variables

To make things easier and to set multiple variables we will use node Node foreman.

Foreman is a manager for Procfile-based applications. Its aim is to abstract away the details of the Procfile format, and allow you to either run your application directly or export it to some other process management format.

First, we need to install globally:

$ npm install -g foreman

Second we need to create a new file called .env at the root of our project.

We can now setup our variables :

{
    "node": {
        "env": "development"
    },
    "port" : 9000,
    "mongo":{
        "name": "username",
        "pass": "mypass"
    }
}

We need to add a new script inside package.json:

"scripts": {
  "start": "node index.js"
}

Now we can run our app with the nf command from node Foreman module that we just installed :

$ nf start

VoilĂ . We now have a clean and flexible setup depending of our environments.

console.log(process.env.PORT) // 9000
console.log(process.env.NODE_ENV) // development
Make sure your variables are fully capitalized.
Nested values are accessibles with an underscore.
View source code Share on twitter