1
votes

I'm running NodeJS Express app,

Currently have dev env, test env, and prod env.

However, the DB connection settings are in the code, is there a secure and best practice way to store DB config and all other configs in JSON file format by declaring them in a module (separately for each env or all in one module to be exported, maybe have a default.JSON, Dev.JSON, Prod.JSON...etc) for each environment then require them accordingly by setting the correct configuration for the correct environment in app.js.

I would like to achieve this without depending on any 3rd party package like .env or ncof.

2

2 Answers

0
votes

Most of the main NodeJs hosting providers uses a simple environment variable. You can use this :

process.env.NODE_ENV

For defining it by yourself, for exemple 'development' on your local, you can do :

NODE_ENV=developpment node yourapp.js

With this, I suggest you to use a config tool, like nconf (there are some good competitors). You can do like this for example :

nconf
    .argv() // Takes arguments from CLI
    .file('./env.' + process.env.NODE_ENV + '.json') // takes from specific env file
    .file('package', './package.json'); // takes from package.json

Here priority is from the most important to the least : 1) argv 2) specific environment file 3) package.json

0
votes

You can require file based on the environment.

const env = 'test';  // This value can be taken from config or .env
const configs = require(`../path/${env}`);
console.log('DB Config', configs.DB_PATH);

Depending on your environment you can load the file. And value for environment can be retrieved from .env or any other config.