JamesG JamesG - 11 months ago 60
Git Question

Using environment variables in Node

I have been trying to get a streamline way of having different environment variables for local and production web apps, but I haven't come across the "ideal" solution yet.

There's the option of having a config.js file like so:

//config.js
{
"secretKey": "SDFDASFFSFD",
"facebook": {
"clientID": "EFGFDGBGDGFS",
"clientSecret": "EGDFNHFG"
}
}


And accessing via ES6 imports

Or using .env files like so:

SOME_KEY=someValue
HELLO=world
FACEBOOK_SECRET=435SDFSF5DZVD7S


And accessing the variables via process.env in the code using dotenv.

Obviously no matter what route you go down, the file will need to be omitted from version control which is fine. Each of these ways are great, but they only seem to work well for local development.

So how do you then have a separate file for a production environment? The dotenv docs say they strongly recommend against a .local.env and .prod.env situation.

Also, how is best to push to a remote server? I have my own server with Gulp tasks which run on a Git post-receive hook. How is best to pass up the production environment variables to here?

Thanks

Answer Source

You could have own config file for each environment:

- environments
  - index.js
  - deveplopment.json
  - staging.json
  - production.json

To use appropriate config file, run the app with required NODE_ENV:

NODE_ENV=production node index

In environments/index.js determinate the current NODE_ENV and use config:

process.env.NODE_ENV = process.env.NODE_ENV || 'development';
module.exports = require('./' + process.env.NODE_ENV);

If config file doesn't include secret info (apiKeys, etc), it can be pushed to repo. Otherwise add it to .gitignore and use environment variables on the server.

Note:

For advanced configuration use such packages as nconf.

It allows to create hierarchical node.js configuration with files, environment variables, command-line arguments, and atomic object merging.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download