Environment dependent Node.js configuration
When you work with Node.js and popular modules like passport, mongoose, etc you will quickly realize 2 things:
- You will make the mistake to push secret keys, usernames or passwords to your public repo. Don’t.
- You will want to use different configurations for different environments. For instance: You will have a need to defined different callback urls for authentication, application keys, database urls, and so forth depending if your application runs in development mode on your local machine, or in production mode when deployed.
There are a number of ways of achieving this, but ideally you want a solution, that:
- elegantly keeps all variables in one place in your application,
- allows you to run and deploy the same code, and
- automagically chooses the right configuration for the right environment,
My standard solution for this is to keep all configuration data in a separate file and make them available via an exported function that returns an objected correlating to the node environments plus provides a default object as fallback.
Let’s look at an example:
The config.js file contains all necessary parameters for my application to run - session key and secret, Twitter App keys for authentication and the path to the database. A version of those are stored in an object with the property name ‘production’ and ‘default’. The exported get function returns the property matching a parameter passed into the function.
Now you can require your configuration data whenever you need it using the get function of our module and passing the environment variable:
var config = require(‘./config.js’).get(process.env.NODE_ENV);
Here you pass in the NODE_ENV variable with which your application gets executed. If you are running in production mode, this will return an object correlating with the production property. But if you were to run the application in development mode (via: NODE_ENV=’Development’ node app.js ) the get function will return the default object, as ‘development’ is not a defined property of the config object in config.js.
Either way you can go ahead and for instance can connect to the correct databases for your current environment by passing the config data like so:
mongoose.connect(config.database, function(…){ … });
I hope this approach helps your to streamline your application configuration & keeps your code cleaner. Please leave comments or suggestions for improvements!
—
Oh and also: add your config.js file to gitignore. Really.