Configuration and environment variables
Reading config from process.env in Node, loading .env files with --env-file instead of dotenv, and validating it once at startup so bad config fails fast.
Configuration and environment variables
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- `process.env` is a flat object of strings. `process.env.PORT` is `"4000"`, never `4000`, and `process.env.DEBUG = "false"` is truthy, so every value needs explicit parsing.
- `node --env-file=.env app.js` loads a dotenv-style file natively, so the `dotenv` package is no longer needed. Repeat the flag to layer files, and a later file overrides an earlier one.
- Variables already set in the real environment win over the file, which is what lets a deploy platform override a checked-in default.
- `--env-file` exits with an error if the file is missing. `--env-file-if-exists` skips it quietly, which suits optional local overrides such as `.env.local`.
- `process.loadEnvFile()` and `util.parseEnv()` do the same job from inside code, for cases where you cannot control the command line.
- Parse and validate all configuration once at startup into one frozen object, and exit non-zero on failure. A missing `DATABASE_URL` should stop the deploy, not surface as a stack trace on the first request.
Why configuration lives outside the code
The same build runs on your laptop, in CI, in staging and in production. What changes between them is small and specific: which database to talk to, which port to listen on, which API key to use, how loud to log. If those values are written into the source, you either edit code per environment or ship secrets in version control. Neither is acceptable.
The usual answer is to read them from the process’s environment. The environment is a set of string key-value pairs that every process inherits from whatever launched it: your shell, a container runtime, a platform’s dashboard. The principle behind it, and why it is the default for hosted apps, is covered in the twelve-factor app and environment config. Keeping secrets out of the repository is in secrets and sensitive data handling. This lesson is the Node side: how the values arrive, and how to make sure they are right before you use them.
process.env and its one big trap
Node exposes the environment as process.env, which you met in the process object. It looks like a normal object, with one important difference: every value is a string.
// PORT=4000 DEBUG=false node a.mjs
console.log(typeof process.env.PORT); // 'string'
console.log(process.env.PORT === 4000); // false
console.log(process.env.DEBUG === 'false'); // true
console.log(!!process.env.DEBUG); // true, because 'false' is a non-empty string
That last line is a classic production bug. A flag that is “off” in the file is “on” in the code. A missing variable is undefined, and an empty one (EMPTY=) is "", which are different things that both fail a truthiness check. Any config you read straight from process.env needs to be parsed on the way in.
Loading a .env file without dotenv
Typing ten variables before every node command does not scale, so the convention is a .env file next to the project. For years that meant installing dotenv and calling it before anything else ran. Node now does this itself, as the video shows:
node --env-file=.env app.js
The file is plain KEY=value lines. Comments start with #, values can be quoted, and an unquoted empty value becomes an empty string. I ran this against a file containing PORT=4000, DEBUG=false, a quoted DATABASE_URL and a single-quoted GREETING='hello world' on Node 26, and each came through as the string you would expect, quotes stripped.
Some behaviour worth knowing, all checked against the local Node:
- Real environment wins. Running
PORT=9 node --env-file=.env app.jsgives the app"9", not the file’s"4000". A platform that injects its own values overrides your defaults, which is what you want. - Later files win.
node --env-file=.env --env-file=.env.local app.jslayers the second over the first, so.env.localcan changePORTto5000. - Missing files are an error by default.
--env-file=.env.nopeprints.env.nope: not foundand exits.--env-file-if-exists=.env.localskips it quietly, so one command line works both on a laptop with local overrides and in CI without them. - Not every dotenv feature is there. The video’s example is the basic case. If you rely on variable expansion (
URL=${HOST}:${PORT}) or on.env.productionfile selection byNODE_ENV, check the docs for what the built-in parser supports before dropping the package.
Two in-process equivalents exist for when you cannot change how the program is launched. process.loadEnvFile('.env') loads a file into process.env, and util.parseEnv(text) parses a string and returns an object without touching process.env, which is handy in tests. The video was recorded when --env-file was new, in Node 20.6, so it predates both and the -if-exists variant. All three work today.
None of this changes the security rules. A .env file holds secrets, so it goes in .gitignore, and a committed .env.example lists the names with dummy values so a new teammate knows what to set.
Validate once, at startup
Loading is half the job. The other half is making sure what you loaded is usable before any request arrives. Scattering process.env.X ?? 'default' through the codebase gives you a different fallback in each file and no early warning. Instead, parse the whole environment into a single typed object, in one module, and refuse to start if it fails.
A schema library does this well. This uses Zod 4, which I ran on Node 26:
// config.mjs
import { z } from 'zod';
const Config = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
PORT: z.coerce.number().int().min(1).max(65535).default(3000),
DEBUG: z.stringbool().default(false),
DATABASE_URL: z.url(),
API_KEY: z.string().min(10),
});
const parsed = Config.safeParse(process.env);
if (!parsed.success) {
console.error('Invalid configuration:\n' + z.prettifyError(parsed.error));
process.exit(1);
}
export const config = Object.freeze(parsed.data);
With API_KEY unset, the process prints Invalid configuration: followed by at API_KEY and exits with code 1. With it set, config.PORT is the number 4000, config.DEBUG is a real false, and nothing else in the app ever touches process.env.
Three habits follow from this:
- Fail loudly and early. Exiting non-zero on bad config makes a broken deploy visible in the orchestrator’s health checks instead of in a customer’s error page.
- One module owns the environment. Everything else imports
config. That makes the app’s inputs readable in one place, and tests can build a config object directly. - Never log the whole object. Print which keys failed, not their values.
Per-environment differences stay small if you let them. The same variables exist everywhere; only their values differ. Avoid if (NODE_ENV === 'production') branches that change behaviour in ways you cannot test locally. NODE_ENV is best treated as a switch that libraries read, not as a place to hide logic.
What the video covers
James Q Quick’s six-minute video is a single demonstration: Node 20.6 added --env-file, so you can run your app with the flag, read variables from process.env, and uninstall dotenv. That is the loading half of this lesson, and it matches the behaviour above. The video does not cover validation, layering, optional files or the in-code functions, and its transcript was not available when this lesson was written, so those parts are carried by the prose. The “go deeper” link from Lazar Nikolov shows the Zod validation pattern in a short demo.
Where this fits
Configuration is the first thing a service reads, and the database URL is usually the first value that matters. Next is SQL databases with Node and connection pools, which uses a validated DATABASE_URL.
Check yourself
Why does `if (process.env.DEBUG)` still run the debug branch when the file says `DEBUG=false`?
Environment variables are always strings, and the string `"false"` is truthy in JavaScript. Compare against the string explicitly, or parse the value once into a real boolean at startup, which is what a schema library does for you.
`PORT=9 node --env-file=.env app.js` and `.env` contains `PORT=4000`. Which port does the app see?
Port 9. A variable that is already set in the process environment is not overwritten by the file, so values set by the shell, the container or the platform win over the checked-in defaults.
You want a developer's `.env.local` to override `.env` when it exists, but CI has no such file. How do you load both?
Pass `--env-file=.env --env-file-if-exists=.env.local`. Files are applied in order and later ones override earlier ones, and the if-exists variant does not fail when the file is absent.
Why validate configuration at startup instead of reading `process.env.X` where it is needed?
A missing or malformed value read lazily fails somewhere unrelated, possibly hours after the deploy and only on the code path that uses it. One schema at startup reports every problem at once, before the process accepts traffic, and gives the rest of the code typed values instead of raw strings.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.