Accessing Environment Variables in Node.js Using `process.env`

Learn how to access environment variables in your Node.js applications using the `process.env` object. This tutorial explains how to retrieve environment variables using dot and bracket notation, demonstrating their use in configuring and customizing your Node.js applications.



Accessing Environment Variables in Node.js Using `process.env`

Node.js provides the `process.env` property to access environment variables. Environment variables are key-value pairs that contain system-specific information or configuration settings. Accessing them allows you to make your Node.js applications more dynamic and adaptable to different environments.

Understanding `process.env`

The `process.env` property is a global object that contains the environment variables available to your Node.js process. This object provides a simple and convenient way to retrieve environment variables without needing to use external libraries or complex system calls. It's very useful for configuration and customization of applications.

`process.env` Syntax


console.log(process.env); //Prints all environment variables.
console.log(process.env.MY_VARIABLE); //Accesses the variable MY_VARIABLE.

You can access individual environment variables using dot notation (e.g., `process.env.MY_VARIABLE`) or bracket notation (e.g., `process.env['MY_VARIABLE']`).

Examples

(Note: The examples below show the output of `console.log(process.env)`. The actual output will vary depending on your system's environment variables. Screenshots from the original text are not included here. Please refer to the original document for visual verification of the examples. The descriptions below aim to convey the information present in those screenshots.)

Example 1: Displaying All Environment Variables

This example prints all the environment variables.

Example 2: Iterating and Displaying Environment Variables

This example iterates through the `process.env` object and prints each key-value pair. It then demonstrates accessing specific environment variables by name.

Example 3: Setting and Deleting Environment Variables

This example shows how to add a new environment variable (`env_proc.myVar`) and then delete it using the `delete` operator. Note that this only affects the current process; it does not modify the system's environment variables.

Example 4: Accessing Process Path and Port

This example shows how to access the process's `PATH` and `PORT` environment variables. It shows how to parse a string environment variable into a number (assuming PORT is a number).