Optimizing your experience
WikipediaWikipedia
Gradient background

How to read Node.js environment variables

Clarice Bouwer

Software Engineering Team Lead and Director of Cloudsure

Tuesday, 18 October 2022 · Estimated 1 minute read

Running a Node app is simple.

bash
Copy
node panic.js

Sometimes you want to add environment variables that either contain sensitive information or are contextual to the environment you want to run your app on. You can set them the moment the process is started.

bash
Copy
NUMBER=42 ANIMAL=dolphins PREFIX=don\'t node panic.js

Imagine having to do this approach with multiple vars and for production ready systems where commands are written to the logs. Not a good idea. This approach is great for testing though.

To access these variables in your code, simply prefix the scream case with process.env..

panic.js
Copy
console.log(`${process.env.NUMBER} is my favorite number.`);
console.log(`${process.env.ANIMAL} are my favourite animals`);
console.log(`${process.env.PREFIX} panic!`);

What you do then is create a hidden environment file in the root of your project most commonly named .env.

Copy
NUMBER="42"
ANIMAL="dolphins"
PREFIX="don't"

If you have multiple environments, you can use dotenv to load them during runtime.

panic.js
Copy
require('dotenv').config();

console.log(`${process.env.NUMBER} is my favorite number.`);
console.log(`${process.env.ANIMAL} are my favourite animals`);
console.log(`${process.env.PREFIX} panic!`);

Note

You don't need to import the dotenv Node package into your codebase. Instead run the command below to run the code and do a module to preload (option can be repeated) to require the dependency(ies).

bash
Copy
node --require dotenv/config panic.js
# or shortened to
node -r dotenv/config panic.js

If you have multiple files for different environments then you can specify the file by appending dotenv_config_path to it.

bash
Copy
node -r dotenv/config panic.js dotenv_config_path=.env-vogsphere

Append dotenv_config_debug=true to the command to print out the values in the file.

References