How I use environment variables with NodeJS

Published

After a small tweet I sent out recently, I noticed a lot of response on it. So it seems that a lot of people are struggling with their NodeJS projects and to be more specific with projects using environment variables. I had similar problems up until I discovered the direnv project on Github.

In my enthusiasm I also sent out a tweet in which I shared my discovery of direnv;

Triggered by the response I had received on it, I decided to tell you guys more about how I use direnv in my NodeJS projects nowadays.

Most of my private NodeJS projects run on Heroku, you know that fancy pants SAAS where you can add a massive amount of cool add-ons to your projects. But how do most of these add-ons facilitate their configuration? With environment variables like MONGOHQ_URL or REDISTOGO_URI. And because they are very project-specific, you don't want to store these in your ~/.profile file or similar, you want to store them alongside your project's source files. This is where direnv comes in handy!

So what's direnv then?

Direnv sells itself as an environment variable manager and that's exactly what it is. Instead of storing the env vars in your global ~/.profile or have some funky code that checks if you run locally and otherwise use env var. You only have to create an .envrc file inside your root project directory. This .envrc file can look something like this:

bash
export SIGNATURE_SECRET=ThisIsAVerySecretSecret

Woops! That definitely looks like something you don't want to add to your code repository, so a best practice is to add the .envrc file to your .gitignore file. If you have installed direnv correctly, you noticed in the command line that direnv warned you about you having changed the .envrc file:

bash
direnv: error .envrc is blocked. Run `direnv allow` to approve its content.

They have built in a very good security check. Maybe it's not you who have changed the file but someone else who wants to do some harm to your project. If you are aware of the changes, you can just run direnv allow and you'll see that the environment variables are loaded by direnv.

How do I install this awesome tool?

The maintainers of direnv have excellent documentation for you about this topic. Please check the github project for more information about installing direnv.

How do I use these env vars in NodeJS?

If you not aware of this, I will explain it in short. It's actually very easy! Let's assume you have added to your project, the .envrc file with the SIGNATURE_SECRET var as mentioned above. Now take a look at the following NodeJS code:

js
console.log(process.env.SIGNATURE_SECRET);

When you run this code in the root of your project - this is very important, otherwise the .envrc file isn't picked up - you'll see the string ThisIsAVerySecretSecret as output.

Hopefully you've enjoyed this article and don't hesitate to give your opinion!