1.5. Configuring environment settings in Node.js

In Node.js applications, it is common to find some logic to use different settings for each of the available environments (development, production, etc.). For example, we can indicate that the application will be executed on a port in the development environment and another on the production environment. The Node.js documentation defines a global variable named. The process variable has a property named env, which is an object that contains the user environment. In this book, we will work with one of the most popular Node.js frameworks: express. Don’t worry if you are not familiar with express as you will be able to learn more about it in Chapter 8, Creating server applications with Node.js.

How to do it…

  1. Express provides us with the application class and its configure method which can be used to set the environment-based settings:
    app.configure('development', function(){
     // development env. specific settings
    });
    app.configure('production', function(){
      // production env. specific settings
    });
    
  2. In production, we can set up the environment and port using the following command:
    $ export port=80
    $ export NODE_ENV=production
    

    In the development environment, we can just use the default express settings (port 3000 and NODE_ENV as development).

  3. To run a Node.js application we normally use the node command and the name of the main JavaScript file in your Node.js application:
    $ node app.js
    
  4. If you need to tests your production environment settings in your development environment you don’t need to modify the code, just run the Node.js application using the following command:
    $ NODE_ENV=production node app.js
    

There’s more…

While the solution above will work, it is recommended to separate code from configuration. You can use a JSON file named env for this purpose. The following env.json file can be used as an example:

{
  "development": {
    "facebook_app_id": "facebook_dummy_dev_app_id",
    "facebook_app_secret": "facebook_dummy_dev_app_secret"
  },
  "production": {
    "facebook_app_id": "facebook_dummy_prod_app_id",
    "facebook_app_secret": "facebook_dummy_prod_app_secret"
  }
}

You can then create a file named common.js file and copy the following code snippet into it:

const env = require('env.json');
exports.config = () => {
  const node_env = process.env.NODE_ENV || 'development';
  return env[node_env];
};

As you can see the common.js will only export the configuration of the current environment. You will then require the common.js file from other Node.js files:

const common = require('./routes/common')
const config = common.config();
const facebook_app_id = config.facebook_app_id;

Shiv Kushwaha

Author/Programmer