Here are two ways to read environment variables in Node.js:
- Using process.env object
- Using an .env File with dotenv
Method 1: Using process.env object
The simplest way to read environment variables in Node.js is to use the process.env object.
Each environment variable is an attribute of the process.env object.
To access a specific environment variable, you can use the dot notation. For example, to access the PORT environment variable, “use the process.env.PORT”.
If you have an environment variable named MY_VARIABLE, you can access its value in your Node.js code as follows:
const main_var = process.env.MY_VARIABLE;
Method 2: Using an .env File with dotenv
To manage your environment variables locally (especially during development), you can “use a .env file and the dotenv package to load these variables.”
Here is the step-by-step guide to using a .env file with dotenv.
Step 1: Install dotenv
npm install dotenv
Step 2: Create a .env file in the root of your project and add your variables
Step 3: In Node.js code, load the .env file using dotenv and then access the variables
const main_var = process.env.MAIN_VARIABLE;
console.log(main_var); // Outputs: value
const another_var = process.env.ANOTHER_VARIABLE;
console.log(another_var); // Outputs: another_value
Note: It’s a good practice to avoid committing your .env file to version control (e.g., Git) to prevent sensitive information from being exposed. Add .env to your .gitignore file to ensure it’s not committed.
Setting Environment Variables Directly When Running Node (Not recommended way)
Before learning this method, this way was not recommended, but I am using it here for the learning purpose.
You can also set environment variables directly when running a Node.js script:
MAIN_VARIABLE=value node your_script.js
In your your_script.js file, you can then access MAIN_VARIABLE, as shown previously.
Security Note (Very Important)
Be careful when logging or exposing environment variables, especially in production environments. They might contain sensitive data like API keys, database passwords, or other secrets. Always ensure that such data is not inadvertently exposed or logged.