🙈 Keeping Secrets Out of Git
Never commit .env files to GitHub — anyone with repo access (or anyone who finds a public repo) could read your secrets straight out of it.
1️⃣ Add .env to .gitignore
.envDo this before your first commit. If
.envis already in Git history, adding it to.gitignoreafterward won't remove past commits — you'd need to rotate the exposed secrets and scrub the history.
2️⃣ What Belongs in .env
Sensitive data that should never appear in your source code:
🗝️ API keys
🔑 Database usernames/passwords
🧪 Auth tokens
🌐 Third-party service credentials (payment processors, email providers, cloud storage)
3️⃣ Share a Template Instead: .env.example
Teammates won't have your .env file (it's gitignored), so they won't know what variables the project needs. Commit a template with empty or placeholder values instead:
PORT=
DB_PASSWORD=Onboarding a new developer becomes: copy
.env.exampleto.env, fill in real values, done.
💡 Real-Life Use Case: Email Service
Imagine integrating an email service like SendGrid.
📄 .env
EMAIL_API_KEY=SG.abcdefg1234📜 email.js
require('dotenv').config();
const sendEmail = () => {
const apiKey = process.env.EMAIL_API_KEY;
console.log(`Using Email API key: ${apiKey}`);
};
sendEmail();🖥️ Terminal Output
node email.jsUsing Email API key: SG.abcdefg1234⚠️ When Something's Wrong
If the .env file is missing, not loaded properly, or the variable name doesn't match:
Using Email API key: undefinedCommon causes:
require('dotenv').config()was never called, or was called aftersendEmail()runs.The
.envfile isn't in the project root, ornodewas run from the wrong directory.A typo in the variable name —
EMAIL_API_KEYin code vs.EMAILAPIKEYin.env.Extra spaces or quotes around the value in
.env(e.g.EMAIL_API_KEY = "SG.abc"instead ofEMAIL_API_KEY=SG.abc).
💡 A quick guard against silent failures — throw early if a required variable is missing, instead of finding out later:
if (!process.env.EMAIL_API_KEY) {
throw new Error('Missing required env var: EMAIL_API_KEY');
}