Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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
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
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
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
Hint
Use backticks ` and ${variable} to insert variables inside strings.
Practice
(1/5)
1. What does process.env in Node.js primarily provide access to?
easy
A. File system paths
B. User input from the console
C. Network socket information
D. Environment variables as strings
Solution
Step 1: Understand what process.env represents
process.env is a special object in Node.js that holds environment variables as strings.
Step 2: Identify the correct usage context
It is used to access configuration values or secrets set outside the code, not file paths or user input.
Final Answer:
Environment variables as strings -> Option D
Quick Check:
process.env = environment variables [OK]
Hint: Remember: process.env holds environment variables as strings [OK]
Common Mistakes:
Thinking process.env reads user input
Confusing process.env with file system APIs
Assuming process.env contains numbers or objects
2. Which of the following is the correct way to access an environment variable named API_KEY in Node.js?
easy
A. process.env.API_KEY()
B. process.env['API_KEY']()
C. process.env.API_KEY
D. process.env.get('API_KEY')
Solution
Step 1: Recall the syntax for accessing environment variables
Environment variables in process.env are accessed like object properties, either with dot notation or bracket notation without parentheses.
Step 2: Identify the correct syntax
Using process.env.API_KEY correctly accesses the variable as a string. The other options incorrectly use function call syntax.
Final Answer:
process.env.API_KEY -> Option C
Quick Check:
Access env vars as properties, no parentheses [OK]
Hint: Use dot or bracket notation without () to access env vars [OK]
Common Mistakes:
Adding parentheses as if env vars are functions
Using .get() method which doesn't exist
Confusing bracket notation with function call
3. Consider this Node.js code snippet:
console.log(process.env.PORT || 3000);
If the environment variable PORT is set to 8080, what will be printed?
medium
A. 8080
B. undefined
C. 3000
D. null
Solution
Step 1: Understand the logical OR operator usage
The expression process.env.PORT || 3000 means if process.env.PORT is truthy, use it; otherwise, use 3000.
Step 2: Evaluate the value of process.env.PORT
Since PORT is set to string "8080" (a truthy value), the expression evaluates to "8080".
Final Answer:
8080 -> Option A
Quick Check:
Env var set? Use it; else default [OK]
Hint: If env var exists and is truthy, || returns it [OK]
Assuming SECRET_KEY is not set in the environment.
medium
A. It will throw a TypeError
B. It will print undefined
C. It will print 0
D. It will print null
Solution
Step 1: Check the value of process.env.SECRET_KEY when unset
If SECRET_KEY is not set, process.env.SECRET_KEY is undefined.
Step 2: Understand what happens calling .length on undefined
Trying to access length property on undefined causes a TypeError because undefined has no properties.
Final Answer:
It will throw a TypeError -> Option A
Quick Check:
Accessing property on undefined throws TypeError [OK]
Hint: Check if env var exists before accessing properties [OK]
Common Mistakes:
Assuming undefined has length 0
Expecting undefined to print as string
Not handling missing env vars safely
5. You want to safely read an environment variable DB_PASSWORD and provide a default of "defaultPass" if it is missing or empty. Which code snippet correctly does this?
hard
A. const password = process.env.DB_PASSWORD ?? "defaultPass";
B. const password = process.env.DB_PASSWORD ? process.env.DB_PASSWORD : "defaultPass";
C. const password = process.env.DB_PASSWORD ? "defaultPass" : process.env.DB_PASSWORD;
D. const password = process.env.DB_PASSWORD && "defaultPass";
Solution
Step 1: Understand the conditional operators for empty strings
The ?? operator only defaults null/undefined, keeping empty strings. Ternary checks truthiness, defaulting falsy values like empty strings.
Step 2: Choose the correct conditional to handle missing or empty strings
The ternary operator process.env.DB_PASSWORD ? process.env.DB_PASSWORD : "defaultPass" returns the env var if it is a non-empty string (truthy), else the default. This safely handles missing or empty values.