Skip to content

Manage multiple environments in node.js using node config

In this tutorial let’s see how to manage multiple environments in node.js using node config. In backend projects, it’s critical to manage multiple environments when you application reaches production level.

Node Config is a sweet little npm package that lets you define a set of default parameters, and extend them for different deployment environments (development, qa, staging, production, etc.).

Configurations are stored in configuration files (JSON or YAML) within your application, and can be overridden and extended by environment variables, command line parameters, or external sources.

Install NPM packages

We need two npm packages to make this work, Config and Cross Env. cross-env makes it easy to run single command without worrying about setting or using the environment variable properly for the platform.

Let’s add these packages to the package.json file.

 "dependencies": {
   ....
    "config": "^3.3.1"
  },
  "devDependencies": {
  ...
     "cross-env": "^7.0.2"
  }

Create configuration files

Now let’s create the configuration files. Inside the root directory of your project create a directory called config and create different json files for each environment.

Each of this file would contain the configuration related to each environment.

For example, development.json would have the following configuration.

{
    "app": {
        "port": 3352,
        "ip":"0.0.0.0",
        "https_port":9004
    },
    "db": "mongodb://devapp:pAsS2fsd@mongodb:27017/rainapp_db"
}

Get values from Config

In the application startup code, in app.js or index.js usually, we need to get this configuration from the config package. The config package looks for config directory inside your project directory and read the configuration from JSON or YAML files.

const config = require("config");

const ip = config.get('app.ip');
const port = config.get('app.port');

Configure startup scripts

The final step is to configure startup scripts in package.json. For each environment (in other words for each configuration file in config directory), we can create a startup script.

  "scripts": {
    "start:dev": "cross-env NODE_ENV=development node app.js",
    "start:qa": "cross-env NODE_ENV=qa cd src && node app.js",
    "start:prod": "cross-env NODE_ENV=production cd src && node app.js",
    "start:demo": "cross-env NODE_ENV=demo cd src && node app.js"
  }

That’s it. You can now start your application in different environments using npm start:<env> command inside your environment. In development server, you can start the application using npm start:dev script.

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.