0
0
NodejsHow-ToBeginner · 3 min read

How to Read Environment Variables in Node.js Easily

In Node.js, you read environment variables using process.env.VARIABLE_NAME. This accesses the variable named VARIABLE_NAME from your system or environment configuration.
📐

Syntax

Use process.env.VARIABLE_NAME to get the value of an environment variable named VARIABLE_NAME. If the variable does not exist, it returns undefined.

  • process.env: A built-in object in Node.js that holds all environment variables.
  • VARIABLE_NAME: The exact name of the environment variable you want to read.
javascript
const value = process.env.MY_VARIABLE;
console.log(value);
Output
undefined
💻

Example

This example shows how to read an environment variable named GREETING. You can set this variable before running the script, and the script will print its value.

javascript
console.log('GREETING:', process.env.GREETING || 'No greeting set');
Output
GREETING: Hello, world!
⚠️

Common Pitfalls

Common mistakes when reading environment variables include:

  • Not setting the environment variable before running the Node.js script.
  • Using the wrong variable name or case sensitivity issues (environment variables are case-sensitive).
  • Expecting environment variables to be automatically loaded from a file without using a package like dotenv.

Always check if the variable exists before using it to avoid undefined values.

javascript
/* Wrong way: Assuming variable is set without checking */
console.log(process.env.MY_VAR.toUpperCase()); // Throws error if MY_VAR is undefined

/* Right way: Check before using */
if (process.env.MY_VAR) {
  console.log(process.env.MY_VAR.toUpperCase());
} else {
  console.log('MY_VAR is not set');
}
Output
MY_VAR is not set
📊

Quick Reference

Tips for working with environment variables in Node.js:

  • Use process.env.VAR_NAME to access variables.
  • Set variables in your shell or use a .env file with the dotenv package.
  • Environment variables are always strings or undefined.
  • Check for existence before using to avoid errors.

Key Takeaways

Use process.env.VARIABLE_NAME to read environment variables in Node.js.
Environment variables must be set in your system or loaded with tools like dotenv.
Always check if the variable exists before using it to avoid errors.
Environment variables are case-sensitive and always strings or undefined.
Use fallback values or checks to handle missing environment variables gracefully.