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!
I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like addEventListener
and attachEvent
. Times have changed but there are still a few functions each developer should...
Firefox OS is all over the tech news and for good reason: Mozilla's finally given web developers the platform that they need to create apps the way they've been creating them for years -- with CSS, HTML, and JavaScript. Firefox OS has been rapidly improving...
If you troll page markup like me, you've no doubt seen the use of data URI's within image src attributes. Instead of providing a traditional address to the image, the image file data is base64-encoded and stuffed within the src attribute. Doing so saves...
As you should already know, the best visual features of a website are usually held within the most subtle of details. One simple trick that usually makes a big different is the use of opacity and fading. Another awesome MooTools functionality is...
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.