Node.js: Code Outside the Browser / Environment Variables & Configurations

Keeping secrets (API keys, DB passwords) out of source code

🙈 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

.env
  • Do this before your first commit. If .env is already in Git history, adding it to .gitignore afterward 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.example to .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.js
Using 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: undefined

Common causes:

  • require('dotenv').config() was never called, or was called after sendEmail() runs.

  • The .env file isn't in the project root, or node was run from the wrong directory.

  • A typo in the variable name — EMAIL_API_KEY in code vs. EMAILAPIKEY in .env.

  • Extra spaces or quotes around the value in .env (e.g. EMAIL_API_KEY = "SG.abc" instead of EMAIL_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');
}