0
0
Node.jsframework~30 mins

process.env for environment variables in Node.js - Mini Project: Build & Apply

Choose your learning style9 modes available
Using process.env for Environment Variables in Node.js
📖 Scenario: You are building a simple Node.js app that needs to use secret keys and settings without hardcoding them in your code. Environment variables help keep these values safe and easy to change.
🎯 Goal: Learn how to create environment variables and access them in your Node.js app using process.env.
📋 What You'll Learn
Create a .env file with specific environment variables
Load environment variables using the dotenv package
Access environment variables in your Node.js code using process.env
Use environment variables to configure app settings
💡 Why This Matters
🌍 Real World
Environment variables are used to keep sensitive data like API keys and passwords out of your code. This helps keep your app secure and flexible.
💼 Career
Knowing how to use process.env and environment variables is essential for backend developers and anyone deploying apps to real servers or cloud platforms.
Progress0 / 4 steps
1
Create a .env file with environment variables
Create a file named .env in your project root. Inside it, write these exact lines:
API_KEY=12345abcde
PORT=3000
Node.js
Need a hint?

The .env file stores key-value pairs like KEY=value. Make sure there are no spaces around the equals sign.

2
Install and configure dotenv package
In your Node.js project, install the dotenv package by running npm install dotenv. Then, in your main file index.js, add this line at the very top:
require('dotenv').config();
Node.js
Need a hint?

This line loads the variables from your .env file into process.env.

3
Access environment variables in your code
In index.js, create two constants named apiKey and port. Assign them the values from process.env.API_KEY and process.env.PORT respectively.
Node.js
Need a hint?

Use process.env.VARIABLE_NAME to get the value of an environment variable.

4
Use environment variables to configure your app
Add a simple console log that outputs: Server running on port {port} with API key {apiKey} using template literals and the constants port and apiKey.
Node.js
Need a hint?

Use backticks ` and ${variable} to insert variables inside strings.