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:

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.