Super simple environment variables in Node.js

I recently made a small project using the Twitter API and wanted a super simple way to store my local environment variables. Fair warning, my method is a little hack-y, but you can riff on it for your own purposes.

The problem

I wasn’t familiar with how to set environment variables in Node, and I didn’t want to pass FOO=BAR every time I ran my script, so I wanted to save them somewhere locally and then ignore the file in git so I didn’t expose my API key to Github, and I’d set it up on my server in the server-appropriate way.

process.env

In Node, you can access environmental variables using process.env, but how to set them? Luckily, it’s as easy as assignment (because this is JavaScript and WHERE WE’RE GOING, WE DON’T NEED ROADS). Here’s an example of an env.js:

When you require('env.js') because this isn’t wrapped in a module.exports (on purpose), the code is literally executed and thus the variables are added to your environment. To load the environmental variables locally, I check to see if one of the variables exists (really you should check them all) and if it doesn’t, then I require my env module, because I assume I’m running locally.

This had the great side benefit of making it very obvious when I was deploying to an external server if I’d set my environmental variables on the server correctly, because if they didn’t exist, Node went looking for this module. Learn more about process.env in the Node docs.

I used this method in the recent project I ran over the weekend, saving #talkpay tweets to a MongoDB database. It has about 26k records, if you’d like to do some analysis on it. The code for the search and the database dump are both on Github.

Tags: , , , ,

12 Responses to “Super simple environment variables in Node.js”

  1. Gonçalo Morais May 4, 2015 at 4:42 pm #

    Yeah, I usually do something like this. And currently, I decided to start using https://github.com/indexzero/nconf

  2. Da5id July 26, 2015 at 1:26 am #

    I really like this approach as it is super simple and highly modular. Thanks for the article!

  3. Da5id July 26, 2015 at 1:15 pm #

    Would it be okay to always require the file but do individual `if` statements for each variable in `env.js`?

    • Pam Selle July 26, 2015 at 3:51 pm #

      Okay? It’s probably a fantastic idea. And you could also abstract the checking block to a function (ex. “validateEnvironmentVars()”).

      • Da5id July 26, 2015 at 11:55 pm #

        That is a great idea. I like the idea of the abstracted check logic. Thanks again!

      • Da5id July 26, 2015 at 11:58 pm #

        Would you mind giving me an example of the `validateEnvironmentVars()`? Not exactly sure how to go about it correctly.

        • Pam Selle July 27, 2015 at 7:41 am #

          You could do multiple things, like adding explicit ifs for each thing you’re using:

          function validateEnvironmentVars() {
          if(!process.env.CONSUMER_KEY || !process.env.MYSECRETTHING || ….) {
          console.error(“Missing environment variable!”)
          return 1
          }
          }

          Other options could be writing an array containing the key names you want and looping through that array – that method would also help you so your error message could contain the missing thing!

          There’s no “correct”, there’s multiple ways to get at the same thing. Hope this helps!

          • Da5id July 27, 2015 at 8:59 pm #

            I was just wondering what the `correct` way to do it is, but I like the first way, that is basically what I came up with as well.

  4. Christian October 18, 2015 at 4:45 pm #

    I just implemented my own JSON environment variable tool. Have a look at it here: https://github.com/cmartin81/configurator (npm json-configurator)

    Write your environment variables inside a JSON and pass the object through the json-configurator. I.E
    var config = {
    ‘test’: ‘abc’,
    ‘foo’: ‘bar,
    $prod_foo: ‘barbar’}

    console.log(require(‘json-generator’)(config, ‘prod’).foo);
    // barbar

  5. Weijing Lin February 3, 2016 at 2:49 pm #

    I see most ppl using process.env

  6. SIRHAMY April 8, 2016 at 4:27 pm #

    Thank you, thank you, thank you. I’ve been looking for a simple explanation like this for quite some time.

  7. Curtis Timson August 15, 2017 at 4:07 am #

    Great approach! Thanks for the helpful suggestion.

    I’m also currently building a simple Twitter application and was wondering how best to use process.env variables locally.

Leave a Reply