Reputation: 144
What's the best way to handle configuration for different environments in an Express app?
Should I place {development, production, testing}.json in /.config and load the appropriate one based on process.env.NODE_ENV? Something like...
var env = process.env.NODE_ENV || 'development';
var config = require('./config/' + env + ".json");
or is there a better way?
Upvotes: 3
Views: 3415
Reputation: 504
I would suggest you to also take a look to the env-dot-prop
package.
It allows you to set/get properties from process.env
using a dot-path
.
Let's assume that your process.env
contains the following:
process.env = {
FOO_BAR: 'baz'
'FOO_🦄': '42'
}
Then you can manipulate the environment variables like that:
const envDotProp = require('env-dot-prop');
console.log(process.env);
//=> {FOO_BAR: 'baz', 'FOO_🦄': '42'}
envDotProp.get('foo');
//=> {bar: 'baz', '🦄': '42'}
envDotProp.get('foo.🦄');
//=> '42'
envDotProp.get('foo.🦄', {parse: true});
//=> 42
envDotProp.set('baz.foo', 'bar');
envDotProp.get('', {parse: true});
//=> {foo: {bar: 'baz', '🦄': 42}, baz: {foo: 'bar'}}
console.log(process.env);
//=> {FOO_BAR: 'baz', 'FOO_🦄': '42', BAZ_FOO: 'bar'}
envDotProp.delete('foo');
envDotProp.get('');
//=> {baz: {foo: 'bar'}}
console.log(process.env);
//=> {BAZ_FOO: 'bar'}
This helps you to parse the environment variables and use them as a config object in your app.
It also helps you implement a 12-factor configuration.
Upvotes: 0
Reputation: 631
I've normally done something like this:
File structure:
config/
config.js
env/
development.js
test.js
production.js
And then inside the config.js
file store universal config things, as well as loading the respective environment config:
// main config.js file
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
// load the config file for the current environment
var config = require('./env/' + process.env.NODE_ENV);
// extend config with universal config data
config.someEnvAgnosticSetting = true;
// export config
module.exports = config;
This allows you to easily separate out environment specific configurations, while allowing any module requiring the config to only need to require the root config file.
For example, in your server.js
file:
// require config, not worrying about what environment is being loaded
var config = require('./config/config');
// use config data
app.listen(config.port);
Edit: BTW, I didn't make this approach up - it's a really common one for node apps (or web apps in general, but it just so happens that in node you need to roll your own setup). Check out the mean.js example app for a more in depth example using this pattern.
Upvotes: 7