0
0
Node.jsframework~30 mins

dotenv for environment configuration in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Using dotenv for Environment Configuration in Node.js
📖 Scenario: You are building a Node.js application that needs to use secret keys and configuration values without hardcoding them in your code. To keep these values safe and easy to change, you will use the dotenv library to load environment variables from a file.
🎯 Goal: Learn how to set up a .env file, load it using dotenv, and access environment variables in your Node.js app.
📋 What You'll Learn
Create a .env file with specific environment variables
Install and import the dotenv package
Configure dotenv to load variables from the .env file
Access and use environment variables in your Node.js code
💡 Why This Matters
🌍 Real World
Many Node.js applications use environment variables to keep sensitive data like API keys and configuration separate from code. This helps keep secrets safe and makes it easy to change settings without editing code.
💼 Career
Understanding how to use dotenv and environment variables is essential for backend developers and anyone working with Node.js apps in real projects, especially when deploying to cloud or production environments.
Progress0 / 4 steps
1
Create a .env file with environment variables
Create a file named .env in your project root folder. Inside it, write these exact lines:
API_KEY=12345abcde
PORT=3000
DEBUG=true
Node.js
Need a hint?

The .env file should have one variable per line in the format KEY=VALUE.

2
Install and import the dotenv package
In your Node.js project, install dotenv by running npm install dotenv. Then, in your main JavaScript file, add this line at the top:
import dotenv from 'dotenv';
Node.js
Need a hint?

Use ES module syntax to import dotenv as shown.

3
Configure dotenv to load environment variables
After importing dotenv, call dotenv.config() to load the variables from the .env file into process.env. Write this exact line:
dotenv.config();
Node.js
Need a hint?

Call dotenv.config() exactly to load the variables.

4
Access and use environment variables in your code
Write code to create three constants named apiKey, port, and debugMode. Assign them the values from process.env.API_KEY, process.env.PORT, and process.env.DEBUG respectively. Use this exact code:
const apiKey = process.env.API_KEY;
const port = process.env.PORT;
const debugMode = process.env.DEBUG;
Node.js
Need a hint?

Use process.env.VARIABLE_NAME to access each environment variable.