Recently, we created a small node.js
module for handling environment variables better. It's called dotenv
and is inspired by the rubygem of the same name
Building modern web applications requires a handful of environment variables that vary between deploys.
The tenets of a twelve-factor app
describe this well. For example, if you are building your own SaaS
product, you might have a Stripe
secret key to process payments and a url to your Postgres
database. Both of these will be different between production and development.
By putting these keys in environment variables, we give ourselves a couple advantages:
- They are easily changeable between environments and even isolated deploys. This leads to less complex deploys which saves time and money.
- There is a decreased chance of the production keys leaking out into the wrong hands or to a junior developer's hands. This leads to less chance that your database might maliciously or accidentally be wiped.
will help you get these advantages for your node.js projects. That's why we think you should use it.
To begin, add the dotenv module to your node.js package.json file. Then as early as possible in your application require dotenv and call load().
var dotenv = require('dotenv');
Finally, create a .env file to store your environment variables in the following format. It is recommended you do not commit this file to version control.
Now, whenever your application loads, these variables will be available in process.env.
var sendgrid_username = process.env.SENDGRID_USERNAME;
Enjoy. Learn more about dotenv at https://github.com/scottmotte/dotenv
Also, some alternatives to dotenv are node-config