tareq3
12/22/2018 - 7:13 PM

Config in node

how to set env variable and use them in node app

Install config npm package

npm i config

create folder config and create two json file

    custom-environment-variables.json

create a key inside default.json

//for secret key keep the value empty string
 {
  "jwtPrivateKey":""
}

for public key like dbhost , dbname provide the values

{
 "dbHost": "localhost",
    "dbPort": 5984,
    "dbName": "node-sequelize"
}

Now attach this key to a environment variable inside custom-environment.variuables.json

// Now we have to assign value from a env vairable
{
  "CONFIG_KEY":"ENVIRONMENT_VARIABLE_KEY"
}

ex:

{
  "jwtPrivateKey":"mti_jwtPrivateKey"
}

That's it we defined our envornment variable : mti_SecretKey

Now set the value of that env variable. inside cmd

windows

set mti_jwtPrivateKey=VALUE_OF_THAT_VARIABLE

Unix:

export  mti_jwtPrivateKey=VALUE_OF_THAT_VARIABLE

How to check a environment variable value

echo $ENVIRONMENT_VARIABLE_NAME

ex:

echo $mti_SecretKey

How to get an Environment variable

process.env.PORT

How to use env variable using config key

const config = require('config');

 config.get('jwtPrivateKey')

Req for setting env variable from server.js//app.js

const config = require('config');

if (!config.get('jwtPrivateKey')) {
    console.error('FETAL ERROR: jwtPrivateKey is not defined.');
    process.exit(1);
}