Environment-based configuration helps your app use different settings for development, testing, and production. This keeps your app flexible and safe.
Environment-based configuration in Express
const express = require('express'); const app = express(); const port = process.env.PORT || 3000; const dbUrl = process.env.DB_URL || 'mongodb://localhost/devdb'; app.listen(port, () => { console.log(`Server running on port ${port}`); });
Use process.env.VARIABLE_NAME to access environment variables.
Provide default values with || to avoid errors if variables are missing.
const port = process.env.PORT || 3000;const secretKey = process.env.SECRET_KEY;
const isProduction = process.env.NODE_ENV === 'production';This Express app uses environment variables for the port and a welcome message. If you set PORT or WELCOME_MESSAGE in your environment, the app uses those. Otherwise, it uses default values.
Try running this app with different environment variables to see how it changes.
const express = require('express'); const app = express(); // Use environment variables or defaults const port = process.env.PORT || 3000; const message = process.env.WELCOME_MESSAGE || 'Hello from Express!'; app.get('/', (req, res) => { res.send(message); }); app.listen(port, () => { console.log(`Server running on port ${port}`); });
Set environment variables outside your code, for example in a terminal or a .env file.
Never commit secret keys or passwords to your code repository.
Use packages like dotenv to load environment variables from a file during development.
Environment-based configuration lets your app change settings without code changes.
Use process.env to access environment variables in Express.
Always provide safe defaults and keep secrets out of your code.
Practice
Solution
Step 1: Understand environment-based configuration
It allows changing settings like ports or database URLs without changing the app code.Step 2: Compare options
Only To change app settings without modifying the code describes this purpose correctly; others contradict the idea of flexible configuration.Final Answer:
To change app settings without modifying the code -> Option AQuick Check:
Environment config = change settings without code [OK]
- Confusing environment config with hardcoded settings
- Thinking environment config restricts app to one machine
- Assuming environment config means no external variables
PORT in an Express app?Solution
Step 1: Recall how to access environment variables in Node.js
Useprocess.env.VARIABLE_NAMEto get environment variables.Step 2: Check each option
const port = process.env.PORT; uses the correct syntax. const port = env.PORT; missesprocess. const port = process.PORT; uses wrong property. const port = process.env['port']; uses lowercase key which is case-sensitive and usually environment variables are uppercase.Final Answer:
const port = process.env.PORT; -> Option AQuick Check:
Use process.env.VAR to access env variables [OK]
- Omitting 'process' before 'env'
- Using wrong casing for environment variable names
- Accessing environment variables as properties of process
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});If the environment variable
PORT is set to 5000, what will be printed when the server starts?Solution
Step 1: Understand the fallback logic
The code usesprocess.env.PORT || 3000, so ifPORTis set, it uses that; otherwise, 3000.Step 2: Apply given environment variable
SincePORTis set to 5000, the server listens on port 5000 and prints that.Final Answer:
Server running on port 5000 -> Option DQuick Check:
Env var set? Use it; else default [OK]
- Ignoring the environment variable and using default
- Printing the variable name instead of its value
- Assuming undefined if environment variable exists
const secret = process.env.SECRET_KEY; console.log(secret.length);
But when you run the app, it crashes with
TypeError: Cannot read property 'length' of undefined. What is the likely cause?Solution
Step 1: Analyze the error message
The error sayslengthis accessed onundefined, meaningsecretis undefined.Step 2: Check environment variable usage
IfSECRET_KEYis not set in environment,process.env.SECRET_KEYis undefined, causing the error.Final Answer:
The environment variable SECRET_KEY is not set -> Option CQuick Check:
Undefined env var causes undefined value [OK]
- Assuming env variable is always defined
- Using wrong property to access env variables
- Not handling undefined values before property access
Solution
Step 1: Understand environment-based config with fallback
Use environment variable if set; otherwise, use a safe default URL.Step 2: Evaluate each option
const dbUrl = process.env.DB_URL || 'mongodb://localhost/devdb'; correctly usesprocess.env.DB_URL || default. const dbUrl = 'mongodb://localhost/devdb'; if (process.env.NODE_ENV === 'production') dbUrl = process.env.DB_URL; tries to reassign a const variable (error). const dbUrl = process.env.DB_URL && 'mongodb://localhost/devdb'; uses && which returns false if DB_URL is missing. const dbUrl = process.env.DB_URL ? 'mongodb://localhost/devdb' : process.env.DB_URL; reverses the condition, causing wrong assignment.Final Answer:
const dbUrl = process.env.DB_URL || 'mongodb://localhost/devdb'; -> Option BQuick Check:
Use env var or fallback default [OK]
- Reassigning const variables
- Using && instead of || for fallback
- Swapping condition logic causing wrong URL
Ready to prove it?
Pass the test and this pattern moves unknown
