Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
164 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...