Lesson 16 / 24
.env Files Done Right
Ignore real .env files, commit a .env.example and validate required variables at startup.
Example in, secret out
Commit .env.example with variable names and fake values so teammates know what to set. Add the real .env to .gitignore before you create it, because ignoring a file already committed does not remove it from history.
Local, repo, CI, production
A secret travels through several places. Each one needs a safe way to receive it.
Fail fast when a variable is missing
Check required variables when the app starts so a missing secret fails loudly instead of causing odd errors later.
const required = ["DATABASE_URL", "STRIPE_KEY"];
for (const name of required) {
if (!process.env[name]) {
throw new Error(`Missing environment variable: ${name}`);
}
}Check .gitignore first
Run git status before your first commit and confirm .env is not listed. Use git check-ignore -v .env to see which rule ignores it.
Quick check: What should be committed for environment configuration?
- .env with real values
- .env.example with placeholder values
- Nothing, ever, not even names
- A zip of .env
Answer
.env.example with placeholder values — The example documents what to set without exposing real secrets.