How I use environment variables with Node.js
After I tweeted about direnv, I noticed that a lot of people were dealing with the same problem in their Node.js projects: project-specific environment variables.
This was the tweet:
Damn it looks like https://t.co/pW1BSAlHRe makes my #nodejs project-based env vars a whole lot easier!
— Robin van der Vleuten (@robinvdvleuten) July 22, 2014
The response made me write down how I use direnv in Node.js projects.
Most of my private Node.js projects ran on Heroku. Heroku add-ons usually expose configuration through environment variables like MONGOHQ_URL or REDISTOGO_URI. Those values are project-specific, so I do not want them in ~/.profile. I want them near the project, without committing them to the repository. That is where direnv helps.
So what's direnv then?
Direnv calls itself an environment variable manager, which is exactly how I use it. Instead of putting variables in your global ~/.profile, or writing application code that checks whether it is running locally, you create an .envrc file in the project root. It can look like this:
bashexport SIGNATURE_SECRET=ThisIsAVerySecretSecret
That is not something you want in the repository, so add .envrc to .gitignore. If direnv is installed correctly, it warns you when the file changes:
bashdirenv: error .envrc is blocked. Run `direnv allow` to approve its content.
That warning is useful. Maybe you changed the file, or maybe someone else changed it and you should read it first. If you trust the change, run direnv allow and direnv loads the variables.
How do I install this awesome tool?
The direnv maintainers already document installation well. Check the GitHub project for current install instructions.
How do I use these env vars in NodeJS?
Node.js exposes environment variables on process.env. If your .envrc contains the SIGNATURE_SECRET value from above, you can read it like this:
jsconsole.log(process.env.SIGNATURE_SECRET);
Run that code from the project root. That part matters, because otherwise direnv does not load the .envrc file. You should see ThisIsAVerySecretSecret as output.
That is enough for most local project configuration.