Easy-loading Environment Variables in Node


Posted on

dotenv

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.

Why we created it

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:

  1. They are easily changeable between environments and even isolated deploys. This leads to less complex deploys which saves time and money.
  2. 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.

Dotenv will help you get these advantages for your node.js projects. That’s why we think you should use it.

How to 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');
dotenv.load();

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.

S3_BUCKET=YOURS3BUCKET
SECRET_KEY=YOURSECRETKEYGOESHERE
SENDGRID_USERNAME=YOURSENDGRIDUSERNAME
SENDGRID_PASSWORD=YOURSENDGRIDPASSWORDGOESHERE

Now, whenever your application loads, these variables will be available in process.env.

For example:

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 and nconf.


Hacker in LA. I believe the future is bright. It's up to us to build it - as programmers we get a big say. Follow me on twitter @motdotla.

Scott Motte on Twitter

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>