Get and Set Environment Variables in Node.js
One of the best ways to use sensitive information in open source repositories without hard-coding the information within publicly available repositories is setting environment variables. Set the environment variables on the server, retrieve them by key within your application.
When using Node.js, you can retrieve environment variables by key from the process.env
object:
var mode = process.env.mode; // 'PRODUCTION', for example
var apiKey = process.env.apiKey; // '38294729347392432'
There are time when you may want to set environment variables while you run your node app -- these are set temporarily while the process is still running. A common case is simulating environment variables during testing. You can temporarily set these variables by pegging items onto the process.env
object:
process.env.mode = 'TESTING';
// Now app code knows not to do destructive transactions!
Simple enough but worth documenting for future use!
![From Webcam to Animated GIF: the Secret Behind chat.meatspac.es!]()
My team mate Edna Piranha is not only an awesome hacker; she's also a fantastic philosopher! Communication and online interactions is a subject that has kept her mind busy for a long time, and it has also resulted in a bunch of interesting experimental projects...
![Vibration API]()
Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user. One of those simple APIs the Vibration API. The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...
![MooTools 1.2 Tooltips: Customize Your Tips]()
I've never met a person that is "ehhhh" about XHTML/javascript tooltips; people seem to love them or hate them. I'm on the love side of things. Tooltips give you a bit more information about something than just the element itself (usually...
![Smooth Scrolling with MooTools Fx.SmoothScroll]()
I get quite a few support requests for my previous MooTools SmoothScroll article and the issue usually boils down to the fact that SmoothScroll has become Fx.SmoothScroll. Here's a simple usage of Fx.SmoothScroll.
The HTML
The only HTML requirement for Fx.SmoothScroll is that all named...
I believe it’s more common to use
process.env.NODE_ENV
instead ofprocess.env.mode
This is an interesting problem. What if you are using aws or heroku for hosting? You could have your deployment script setup the keys, but you’d need to prompt each time you create a new instance.
I encrypted the keys in a json file with AES 256 and in my run/deploy script it prompts for a password and decrypts it running the rest of the application with env variables. It’s not perfected yet, but this might be a good way to put it on github.
Are these variables just being set via the command line?
Yep!
I have had great success with json-configurator (https://www.npmjs.com/package/json-configurator). Use it with
process.env.NODE_ENV
as a input.