Node.js Environment Variables
Environment variables allow Node.js applications to read configuration values from their execution environment. They help us configure applications without changing the source code.
1. What Are Environment Variables?
Environment variables are named values provided to an application by its operating system, terminal, deployment environment, or configuration setup.
For example, a Node.js application may need an application name, server port, or environment name. Instead of hardcoding these values, we can read them from environment variables.
Common examples of environment variables are:
APP_NAME— application name.PORT— server port number.NODE_ENV— application environment.DB_HOST— database server configuration.
2. Understanding process.env
Node.js provides the process.env object to access
environment variables available to the running process.
We can read a particular variable by using its name as a property
of process.env.
Example
console.log(process.env.APP_NAME);
console.log(process.env.PORT);
console.log(process.env.NODE_ENV);
Possible Output
CIITApp
5000
development
Explanation:
These values appear when the corresponding environment variables
have been configured. If a variable is missing, its value may be
undefined.
3. Environment Variables Workflow Diagram
This diagram shows how environment variables are supplied to a
Node.js application and accessed through process.env.
Operating System / Terminal
Provides configuration values
Environment Variables
APP_NAME, PORT, NODE_ENV
Node.js process.env
Reads the configured values
Node.js Application
Uses configuration to perform its work
Note: This is a simplified learning diagram showing the basic flow of configuration values.
4. How to Set Environment Variables
Environment variables can be set in the terminal before running a Node.js program. The command depends on the terminal being used.
Windows Command Prompt (CMD)
set APP_NAME=CIITApp
set PORT=5000
node app.js
Windows PowerShell
$env:APP_NAME = "CIITApp"
$env:PORT = "5000"
node app.js
Linux / macOS Terminal
APP_NAME=CIITApp PORT=5000 node app.js
Explanation: These commands configure environment variables for the Node.js process. In CMD and PowerShell, the variables also remain available in the current terminal session until changed or the session ends.
5. Practical Program Using Environment Variables
Let us create a program that reads the application name, environment name, and port number from environment variables.
Step 1: Create a File
Create a file named app.js.
Step 2: Write the Program
const appName = process.env.APP_NAME || "DefaultApp";
const environment = process.env.NODE_ENV || "development";
const port = process.env.PORT || "3000";
console.log("Application Name:", appName);
console.log("Environment:", environment);
console.log("Port:", port);
Step 3: Run the Program
In Windows Command Prompt, execute:
set APP_NAME=CIITApp
set NODE_ENV=development
set PORT=5000
node app.js
Step 4: Expected Output
Application Name: CIITApp
Environment: development
Port: 5000
Step 5: Understand the Program
-
process.env.APP_NAMEreads the application name. -
process.env.NODE_ENVreads the environment name. -
process.env.PORTreads the configured port. -
The
||operator provides a fallback when the environment variable value is falsy.
6. Using a .env File
A .env file stores configuration values in
key-value format. It is commonly used during local development.
Example .env File
APP_NAME=CIITApp
NODE_ENV=development
PORT=5000
In Node.js versions that support the built-in
--env-file option, the file can be loaded while
starting the application.
Run the Program
node --env-file=.env app.js
After the file is loaded, the application can read its values
using process.env.
.env files out of
version control and protect sensitive production configuration.
7. Validating an Environment Variable
Because environment variable values are generally strings, we should validate values before using them in important operations. The following example checks whether a port is a valid integer.
const rawPort = process.env.PORT ?? "3000";
const port = Number(rawPort);
if (
!Number.isInteger(port) ||
port < 1 ||
port > 65535
) {
throw new Error("PORT must be a valid port number.");
}
console.log("Validated Port:", port);
Expected Output
Validated Port: 5000
Explanation:
If PORT is set to 5000, the program
converts the value to a number and validates its range.
If the value is invalid, the program throws an error.
8. Common Mistakes
| Mistake | Reason | Solution |
|---|---|---|
| Variable is undefined | The variable has not been set or loaded. | Check the terminal command or configuration file. |
| Using a string as a number | Environment values are generally strings. | Convert and validate the value. |
| Incorrect variable name | The configured name does not match the code. | Use consistent variable names. |
| Exposing sensitive values | Credentials are stored in committed source code. | Use secure configuration and secret management. |
| Old configuration values | The running process still has previously loaded values. | Restart the application after changing configuration. |
9. Practice Task
Application Configuration Program
Create a Node.js program that reads configuration values from environment variables.
Requirements:
- Read the application name from
APP_NAME. - Read the environment from
NODE_ENV. - Read the port number from
PORT. - Display all three values in the terminal.
- Provide suitable defaults for optional values.
- Validate the port before using it.
Important Points
-
process.envis used to access environment variables. - Environment variable values are generally strings.
- Terminal commands can set variables before running a program.
-
A
.envfile can organize local configuration. - Validate configuration values before using them.
- Never expose real passwords or API keys in source control.
Summary
Environment variables provide configuration values to Node.js
applications. The process.env object allows us
to access these values. We can set variables through the
terminal or load them from a supported .env file.
Values should be validated before use, and sensitive configuration
must be protected from unauthorized access.