Environment Variables and process.env in JavaScript

This article provides an overview of environment variables, their role in software development, and how Node.js accesses them using the global process.env object. You will learn what environment variables are, why they are essential for managing sensitive data and environment-specific configurations, and how to define, read, and manage them effectively in your JavaScript applications.


What Are Environment Variables?

Environment variables are dynamic key-value pairs stored by the host operating system or execution environment outside of an application’s source code. They allow developers to configure application behavior without altering the code itself.

Common use cases include: * Storing sensitive credentials such as database passwords, API keys, and authentication secrets. * Configuring deployment settings such as port numbers (PORT) and hostnames. * Setting execution modes, such as toggling between development, staging, and production via NODE_ENV.

Separating configuration from source code follows modern architectural best practices, keeping sensitive data out of version control repositories.


Accessing Environment Variables with process.env

In Node.js, the runtime automatically injects the system’s environment variables into a global object called process.env.

The process object is a core global module, meaning you do not need to use require or import to access it. The env property contains an object where every key represents an environment variable name, and its value is always a string.

Example: Reading a Variable

const port = process.env.PORT || 3000;
const environment = process.env.NODE_ENV;

console.log(`Server running in ${environment} mode on port ${port}`);

If an environment variable is not defined, process.env.VARIABLE_NAME evaluates to undefined.


Setting Environment Variables

1. Inline via the Command Line

You can define environment variables temporarily when launching your Node.js process:

Linux / macOS:

PORT=4000 NODE_ENV=production node app.js

Windows (PowerShell):

$env:PORT="4000"; $env:NODE_ENV="production"; node app.js

2. Using a .env File (Local Development)

For local development, hardcoding inline variables in the terminal can become cumbersome. A common practice is storing variables in a .env file in the root of the project:

PORT=5000
DB_HOST=localhost
DB_PASS=secretpassword123

To load these variables into process.env, use a package like dotenv:

npm install dotenv

At the top of your main entry file:

require('dotenv').config();

console.log(process.env.DB_HOST); // Outputs: localhost

Key Considerations and Best Practices