When I began using Cloudno.de recently to have a go at Node.js and CouchDB I stored my username and password in plain text in a configuration file. If you are also looking to get CouchDB going with CloudNo.de then my earlier Getting started with Node.js and CouchDB post may be of interest.

The configuration file was fine for testing as nobody who came across the database login details could do any real damage, but as the project got more interesting I wanted to send it live and these details would need to be kept private.

Thankfully the Nodester platform, which CloudNo.de is using, has environment variables built in and you can use them to store sensitive data such as passwords. It is also good to know that the variables will persist even after the host machine is cycled.

To set an environment variable you simply make a curl request to the API like the following:

curl -k -X PUT -u "[username]:[api key/password]" -d "appname=[app name]&key=[environment variable name]&value=[environment variable value]" https://api.cloudno.de/env

Replace the items in the square brackets with the values from your Nodester based hosting solution (such as cloudno.de) and your environment variable content.

If you are not using CloudNo.de then you will also need change the URL at the end of the command above to point to the correct API URL for your service. For example with Nodester’s own hosting the URL should be http://api.nodester.com/env.

So if I wanted to set an environment variable called “first_name” and set the value to “Simon” I would issue the following curl request.

curl -k -X PUT -u "username:api_key" -d "appname=app_name&key=first_name&value=Simon" https://api.cloudno.de/env

To check it has been set correctly you can GET the value:

curl -u "[username]:[api key/password]" -d "appname=[app name]&key=[environment variable name]" https://api.cloudno.de/env

You can also delete an environment variable from the system using the following command:

curl -X DELETE -u "[username]:[api key/password]" -d "appname=[app name]&key=[environment variable name]" https://api.cloudno.de/env

So that sets up the environment variable, but how do you access it from within Node.js?

It is as simple as accessing the global process object in the following manner:

var environment_variable_value = process.env.[environment variable name];

Again replace the square brackets with the actual environment variable name to access it. So to access the environment variable I set in my earlier example it would look like:

var environment_variable_value = process.env.first_name

Now you have a working environment variable setup to store you sensitive data in.