Environment variables let your program use settings that can change without changing the code.
process.env is how Node.js reads these settings.
process.env for environment variables in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Node.js
const value = process.env.VARIABLE_NAME;
VARIABLE_NAME is the name of the environment variable you want to read.
Environment variables are always strings or undefined if not set.
Examples
Node.js
const port = process.env.PORT;
Node.js
const secret = process.env.SECRET_KEY || 'defaultSecret';Node.js
console.log(process.env.NODE_ENV);
Sample Program
This program reads the PORT environment variable and prints which port the server will use. If PORT is not set, it uses 8000.
Node.js
// Save this as example.js // Run with: PORT=3000 node example.js const port = process.env.PORT || '8000'; console.log(`Server will run on port: ${port}`);
Important Notes
Environment variables are set outside your code, often in the terminal or in a .env file.
Use packages like dotenv to load variables from a file during development.
Always check if a variable exists before using it to avoid errors.
Summary
process.env lets Node.js read environment variables as strings.
Use it to keep secrets and settings outside your code.
Always provide defaults or check for undefined to keep your app safe.
Practice
1. What does
process.env in Node.js primarily provide access to?easy
Solution
Step 1: Understand what process.env represents
process.envis 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 DQuick 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
Solution
Step 1: Recall the syntax for accessing environment variables
Environment variables inprocess.envare accessed like object properties, either with dot notation or bracket notation without parentheses.Step 2: Identify the correct syntax
Usingprocess.env.API_KEYcorrectly accesses the variable as a string. The other options incorrectly use function call syntax.Final Answer:
process.env.API_KEY -> Option CQuick 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:
If the environment variable
console.log(process.env.PORT || 3000);
If the environment variable
PORT is set to 8080, what will be printed?medium
Solution
Step 1: Understand the logical OR operator usage
The expressionprocess.env.PORT || 3000means ifprocess.env.PORTis truthy, use it; otherwise, use 3000.Step 2: Evaluate the value of process.env.PORT
SincePORTis set to string "8080" (a truthy value), the expression evaluates to "8080".Final Answer:
8080 -> Option AQuick Check:
Env var set? Use it; else default [OK]
Hint: If env var exists and is truthy, || returns it [OK]
Common Mistakes:
- Assuming PORT is a number, not a string
- Expecting default 3000 even when PORT is set
- Confusing undefined with null
4. What is the main issue with this code snippet?
Assuming
const secret = process.env.SECRET_KEY; console.log(secret.length);
Assuming
SECRET_KEY is not set in the environment.medium
Solution
Step 1: Check the value of process.env.SECRET_KEY when unset
IfSECRET_KEYis not set,process.env.SECRET_KEYisundefined.Step 2: Understand what happens calling .length on undefined
Trying to accesslengthproperty onundefinedcauses aTypeErrorbecause undefined has no properties.Final Answer:
It will throw a TypeError -> Option AQuick 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
Solution
Step 1: Understand the conditional operators for empty strings
The??operator only defaultsnull/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 operatorprocess.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.Final Answer:
const password = process.env.DB_PASSWORD ? process.env.DB_PASSWORD : "defaultPass"; -> Option BQuick Check:
Use ternary to handle empty or missing env vars [OK]
Hint: Use ternary to check for empty or missing env vars [OK]
Common Mistakes:
- Using ?? which allows empty strings through
- Using && which returns wrong value
- Swapping the ternary branches
