Environment Variables in Node.js

Environment variables are values associated with the environment in which a Node.js process runs. They can be used to configure application behavior, manage secrets, and define runtime options. Node.js provides built-in APIs for interacting with environment variables, and .env files are commonly used to manage them in a structured way.

process.envCLI environment variablesdotenv filesvariable names and valuescomments and spacing

~2 min read • Updated Dec 27, 2025

1. CLI Environment Variables


Node.js supports a set of environment variables that can be defined to customize its behavior. These are documented in the CLI Environment Variables section of the Node.js documentation.


2. process.env


The primary API for interacting with environment variables is process.env. It is an object containing pre-populated environment variables that can be modified or expanded at runtime.


3. DotEnv and .env Files


.env files are text files that define environment variables in key-value format. They are widely used across programming languages and platforms, popularized by the dotenv package.


MY_VAR_A = "my variable A"
MY_VAR_B = "my variable B"

File names are usually .env or start with .env (e.g., .env.dev), but this is not mandatory.


4. Variable Names


Valid variable names must match the regex ^[a-zA-Z_]+[a-zA-Z0-9_]*$. They can contain letters, digits, and underscores, but cannot begin with a digit.


Examples of valid names: MY_VAR, MY_VAR_1, myVar. Invalid names: 1_VAR, my-var, VAR_#1.


5. Variable Values


Values can be any text, optionally wrapped in quotes. Quoted values can span multiple lines, while unquoted values must be single-line. All values are interpreted as strings in Node.js.


MY_SIMPLE_VAR = a simple value
MY_EQUALS_VAR = "contains an = sign!"
MY_HASH_VAR = 'contains a # symbol!'

6. Spacing


Whitespace around keys and values is ignored unless enclosed in quotes.


7. Comments


Lines starting with # are comments. Hash symbols inside quotes are treated as normal characters.


# This is a comment
MY_VAR = my value # Inline comment
MY_VAR_A = "# not a comment"

8. Export Prefixes


The export keyword can be added before variable declarations. It is ignored by Node.js but allows the file to be sourced in shell terminals.


export MY_VAR = my value

9. CLI Options


.env files can populate process.env using CLI options:


  • --env-file=file
  • --env-file-if-exists=file

10. Programmatic APIs


  • process.loadEnvFile: Loads an .env file and populates process.env.
  • util.parseEnv: Parses raw content of an .env file and returns its values.

Conclusion


Environment variables in Node.js provide a flexible way to configure applications. With process.env, CLI options, and .env files, developers can manage configuration, secrets, and runtime behavior in a clean and consistent manner.


Written & researched by Dr. Shahin Siami