chovy
chovy

Reputation: 75864

overriding config.js variables for express/node app based on environment

I have a config.js that has all my variables setup.

I want to create a config.global.js and have config.production.js override a few of them and config.development.js override a few of them.

Here's an example config.development.js:

var config = {};    

config.env = 'development';
config.hostname = 'example.dev';
config.appname = 'Example.com';
config.site_url = 'http://example.dev:8080';

module.exports = config;

I am thinking I can just do this in config.development.js (and config.production.js) to override:

var config = require('config.global.js');

config.env = 'development';
config.hostname = 'example.dev';
config.appname = 'Example.com';
config.site_url = 'http://example.dev:8080';

module.exports = config;

And then in app.js, I could do this:

var cfg = require('config.' + ( process.ENV.APP_ENV || 'development' ) + '.js');
app.set('domain', cfg.hostname);

What are some other ways to define application config variables?

Upvotes: 2

Views: 4217

Answers (2)

ebohlman
ebohlman

Reputation: 15003

If you follow himanshu's advice and use a single config file, you can use prototypal inheritance to avoid duplication:

var config = {};    

config.base = {};
config.base.env = 'development';
config.base.hostname = 'example.dev';
config.base.appname = 'Example.com';
config.base.site_url = 'http://example.dev:8080';

config.development = Object.create(config.base);
config.development.debugLevel = 'high';
...

config.production = Object.create(config.base);
config.production.debugLevel = 'low';
...

module.exports = config;

Object.create() is an ES5 function that creates a new empty object with a specified prototype.

Upvotes: 2

himanshu
himanshu

Reputation: 2205

Why not use one JSON file with settings for all the environment. Your approach may not scale well when you introduce more environments. You can get the correct set of properties by looking up NODE_ENV property and using it to pick set of properties from your environment.

I blogged about it sometime ago in Bootstraping a Node.js App for Dev/Prod Environment. Specifically read "Simulating production environment during testing" for an example of how to do it.

Upvotes: 3

Related Questions