How to set process.env

In Node, environment variables are exposed through “process.env”. This seems to be set-able for the current process, although these changes aren’t supposed to go out to the OS.

Most applications use environment variables heavily during startup, as it lets you keep secrets out of the code1.

If you want to set one of these when the application starts, you can set them in your package.json file – cross-env is made to work on both Linux, OS X, and Windows. “NODE_ENV” is used by the Express.js HTTP server (other values being “development” and “production”

"scripts": {
  "test": "cross-env NODE_ENV=test karma start",
}

A good way to get more control over environment variables within the application is to switch to a utility like nconf1, which lets you set up a hierarchical structure of where configuration comes from – the environment, local JSON, etc:

import * as nconf from 'nconf';

nconf.argv()
   .env()
   .file({ file: 'env.json' });

const secret = nconf.get('GOOGLE_SECRET')

If you do this, you could make files like “production.secrets.json”, “development.secrets.json”, add these to .gitignore, and use them to store database passwords and the like.

  1. https://devcenter.heroku.com/articles/config-vars [] []

Leave a Reply

Your email address will not be published. Required fields are marked *