JamesG JamesG - 2 years ago 119
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:

"secretKey": "SDFDASFFSFD",
"facebook": {
"clientSecret": "EGDFNHFG"

And accessing via ES6 imports

Or using .env files like so:


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?


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.


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