How Do Environment Variables Work in Node.js?
Learn how Node.js environment variables work with process.env, .env files and --env-file to configure apps and keep secrets out of your code.
Expected Interview Answer
Environment variables are key-value pairs supplied by the operating system or shell that Node.js reads at runtime through the process.env object, letting you configure an app without changing its code.
Node exposes every variable available to the process as a string property on process.env, so DATABASE_URL or PORT can differ between development, staging and production while the code stays identical. They are commonly loaded from the shell, a container runtime, a CI secret store, or a .env file parsed by a library like dotenv (or Node's built-in --env-file flag). Because they live outside the source tree, they are the standard way to keep secrets such as API keys and passwords out of version control.
- Keeps secrets and config out of source code
- Same build runs across dev, staging and production
- Easy to change without redeploying code
- Works naturally with Docker, CI and cloud platforms
- Central place to manage credentials and toggles
AI Mentor Explanation
Think of a match played under local ground rules: the same team and same players adapt to boundary size, pitch type and daylight without rewriting the rulebook. Environment variables are those ground conditions handed to your app at the start of play, so identical code behaves correctly whether the venue is a dev laptop or a production stadium.
Step-by-Step Explanation
Step 1
Set the variable
Export it in the shell (export PORT=3000), define it in a container/CI config, or list it in a .env file.
Step 2
Load it if needed
For .env files, run node --env-file=.env app.js or call require('dotenv').config() early in startup.
Step 3
Read via process.env
Access values as strings, e.g. const port = process.env.PORT — every value is a string, even numbers.
Step 4
Validate and default
Convert and check types, e.g. const port = Number(process.env.PORT) || 3000, and fail fast if a required var is missing.
Step 5
Keep secrets out of git
Add .env to .gitignore and provide a committed .env.example listing required keys without their values.
What Interviewer Expects
- Knows process.env exposes variables as strings
- Can explain why config is separated from code
- Mentions .env files, dotenv, or node --env-file
- Understands secrets should not be committed
- Handles missing values and type conversion
Common Mistakes
- Assuming process.env values are numbers or booleans, not strings
- Committing .env files with real secrets to version control
- Not providing defaults or validation for required variables
- Confusing build-time and runtime variables
- Hardcoding config directly in source instead of using env vars
Best Answer (HR Friendly)
“Environment variables are settings the computer gives an app when it starts, like which database or port to use. They let the same program run in different places without rewriting the code, and they keep passwords and keys out of the code itself.”
Code Example
// Load variables from a .env file (Node 20.6+):
// node --env-file=.env app.js
// Or with the dotenv package:
// require('dotenv').config();
const port = Number(process.env.PORT) || 3000;
const dbUrl = process.env.DATABASE_URL;
if (!dbUrl) {
throw new Error('DATABASE_URL is required but was not set');
}
console.log(`Starting on port ${port}`);
// process.env values are always strings:
console.log(typeof process.env.PORT); // 'string'Follow-up Questions
- Why are all process.env values strings, and how do you handle numbers or booleans?
- What is the difference between build-time and runtime environment variables?
- How does node --env-file differ from the dotenv package?
- How would you manage secrets in production instead of a .env file?
- What happens if two sources set the same variable?
MCQ Practice
1. What is the data type of a value read from process.env in Node.js?
Every property on process.env is a string, so numeric or boolean settings must be converted explicitly.
2. Which built-in Node flag loads variables from a .env file without any package?
Node 20.6+ supports node --env-file=.env to load variables natively, no dotenv package required.
3. What is the main reason to store secrets in environment variables?
Env vars keep API keys and passwords outside the code, so secrets are not committed to version control.
Flash Cards
How do you read an environment variable in Node.js? — Through process.env.NAME, which returns the value as a string (or undefined if not set).
Why use environment variables instead of hardcoding config? — They let the same code run across dev, staging and production and keep secrets out of the source tree.
What type are process.env values? — Always strings — convert to Number or Boolean yourself when needed.
How can Node load a .env file without dotenv? — Run node --env-file=.env app.js (Node 20.6+).