Environment Variables & Config
Keep secrets and per-environment settings out of your code, so the same code runs safely in development, testing, and production.
What is it?
A backend needs to know things like which database to use, which API key sends emails, and whether it's in development or production. Writing those values into the code causes problems. A secret key in a file gets committed to version control for anyone with repo access to see. A database address hardcoded for your laptop breaks on a production server.
Environment variables are values set outside the code, in the environment the program runs in, and read at startup. Your code asks "what does the environment say this value is?", and each environment (your laptop, staging, production) can give a different answer.
Explain like I'm 10
Think of a recipe that says 'add the number of servings you need' instead of 'serves 4.' The same card works for 2 people or 20. You supply a different number without editing the recipe.
Examples
Reading configuration from the environment
// .env file (never committed to version control)
DATABASE_URL=postgres://localhost:5432/myapp_dev
STRIPE_SECRET_KEY=sk_test_abc123
PORT=3000
// app.js
require("dotenv").config();
const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;
app.listen(port, () => console.log(`Listening on ${port}`));The secret values live in a .env file excluded from version control. The code only refers to process.env.DATABASE_URL by name.
Switching behavior per environment
const isProduction = process.env.NODE_ENV === "production";
if (isProduction) {
app.use(compressionMiddleware());
logger.level = "warn";
} else {
logger.level = "debug";
}One variable, NODE_ENV, lets the same code behave differently depending on where it's deployed.
How it works
Environment variables are set at the operating system or process level, outside your source code. In production, a hosting platform usually lets you set them in a dashboard or config file separate from the codebase.
Locally, a .env file plus a small library (like dotenv) does the same job by loading values into process.env at startup. Your code reads from process.env instead of containing the values.
Why does it exist?
Secrets committed to source control stay in the repo's history forever, even if you delete them later. That's a serious risk if the repo is ever exposed. The same code also needs different settings in different places, like a local database versus a production one.
Environment variables solve both: secrets stay out of the codebase, and config changes per environment without touching the code.
When to use it
Use environment variables for anything sensitive (API keys, database credentials, tokens) or anything that differs between environments (a port, a feature flag, which environment the app is in).
When not to use it
Values that never change and aren't sensitive, like a constant used in one calculation, don't need to be environment variables. That only adds indirection. Keep real constants in code.
Common mistakes
Committing a real
.envfile (with actual secrets) instead of adding it to.gitignore.Forgetting to set a required variable in production, so the app crashes or quietly misbehaves.
Hardcoding a fallback secret in code 'just for now' and forgetting to remove it before shipping.
Practice exercises
- Easy:
Move a hardcoded database URL out of a source file into a
.envfile, and read it viaprocess.env. - Medium:
Use
NODE_ENVto log at 'debug' level in development and 'error' level in production. - Hard:
Explain what could go wrong if a required environment variable is missing in production, and how you'd make the app fail loudly at startup instead of silently.
Interview questions
What are environment variables and why are they used?
Config values supplied by the environment a program runs in, not hardcoded in source. They keep secrets out of the codebase and let the same code adapt to different environments.
Why shouldn't secrets be committed to version control?
They stay in the repo's history even after you remove them, and anyone with repo access, now or later, can see them.
What's the role of a `.env` file in local development?
It simulates real environment variables locally. A library like dotenv loads its key-value pairs into process.env at startup, so the secrets don't live in the source code.
What data type is a value read from `process.env`?
Always a string. PORT=3000 becomes the string "3000", so numbers and booleans need explicit conversion, like Number(process.env.PORT).
What's the difference between `.env` and `.env.example`?
.env holds real, often secret values and is not committed. .env.example lists the variable names the app expects, with placeholders or no values, and is committed so new developers know what to set up without seeing a real secret.
Why is it good practice to make an app fail immediately at startup if a required environment variable is missing, instead of defaulting silently?
Failing at startup shows the misconfiguration right away, in an obvious place. A silent default (say, an empty string) lets the app look healthy, then fail confusingly much later, deep in unrelated code, when the value is finally used.
What does `NODE_ENV` typically control in a Node.js app?
It's a convention that many libraries and your own code check. For example: verbose logging and no caching in development, compression and minimal logging in production.
If a variable is set both in the actual shell environment and in a `.env` file, which one takes effect?
The shell value. Most .env loaders, like dotenv, only set a key in process.env if it isn't already there, so the real OS/shell environment wins over the .env file.
Why is it risky to let a database URL or private API key end up in frontend/client-side code, even unintentionally?
Anything shipped to the browser is visible in dev tools or the page source. A backend-only secret becomes public as soon as it's bundled into client-side JavaScript.
What's the difference between a build-time and a runtime environment variable in a typical deployment?
A build-time variable is baked into the compiled output, so changing it needs a rebuild. A runtime variable is read each time the process starts, so a restart with a new value is enough.
Why do frontend build tools like Vite require a special prefix (e.g. `VITE_`) before exposing an environment variable to client code?
Only variables that opt in with the prefix get bundled into client code. This stops the rest of the environment, including backend-only secrets, from being shipped to the browser by accident.
If you edit a value in `.env` while the app is already running, does the change take effect immediately?
No. Environment variables are read into process.env once, at startup. The running process keeps the old value until you restart it.
What's a feature flag, and how does it typically relate to environment variables?
A toggle that turns a feature on or off without a code change. It's often an environment variable the code checks, so a feature can be on in staging and off in production with the same code.
Why might a production system use a dedicated secrets manager (like AWS Secrets Manager or HashiCorp Vault) instead of plain environment variables?
It adds what plain environment variables lack: encryption at rest, fine-grained access control, audit logs of who read a secret and when, and rotating a credential without redeploying every service that uses it.
What does the "12-factor app" methodology say about configuration?
Store config in the environment, strictly separate from code. The same build should deploy to any environment just by supplying different environment variable values, with no code changes.
What's wrong with code like `if (process.env.DEBUG) { ... }` when the intent is to check a boolean flag?
Every process.env value is a string, so any non-empty string is truthy, including "false". DEBUG=false still enters the debug branch. Compare explicitly: process.env.DEBUG === "true".
Why should different environments (development, staging, production) generally use different actual secret values, not just structurally similar ones?
If one credential is reused everywhere, a leak in a less-protected environment like staging exposes production too. Separate values limit the damage to the environment that leaked.
What's a practical way to validate that all of an app's required environment variables are present and well-formed, rather than checking each one individually wherever it's used?
Define a schema (with zod, envalid, or by hand) listing each variable, its type, and whether it's required. Validate process.env against it once at startup, so a missing or malformed variable crashes the app right away with one clear error.