How to Use Different Environment Config with Node.js

2014/05/032 min read
bookmark this
Responsive image

Table of Contents

  1. Using node-env-file
  2. Tips

Introduction

Depending on the running environment, you may need to use different configuration files. In the Node.js world, the following module is one of the options.

Using node-env-file

Everything is on the following link:

https://www.npmjs.org/package/node-env-file

  1. First, you need to install the node-env-file module.
npm install node-env-file --save

This command will update package.json and install the node-env-file module.

  1. Create your environment file, like .env. The name can be anything, such as .env_dev or .env_prod.
PORT=9000
NODE_ENV=development
  1. Add the following code to your Node.js server-side code. This will use the node-env-file module to replace your process.env.{your variable}.
var env = require('node-env-file');
env(__dirname + '/.env');

Tips

When you want to set the value to empty, you can set it like this:

IP=''

If your code is like the following, it will use 127.0.0.1 instead.

process.env.IP || '127.0.0.1'

Conclusion

The node-env-file module provides a simple way to manage different environment configurations in Node.js. By creating separate .env files for each environment, you can easily switch between development, testing, and production settings without modifying your application code.