Secrets Management

Secrets are DB passwords, API keys, JWT secrets and private keys. Bots scan public GitHub for leaked keys within minutes.

Packages and tools

ToolUse
dotenvLoad .env in local development (Node 20.6+ also has node --env-file=.env)
envalid / zodValidate that the required env vars exist at startup
AWS Secrets Manager / GCP Secret Manager / Azure Key VaultStore secrets in production
HashiCorp VaultSelf-hosted secret store, dynamic DB credentials
gitleaks / trufflehogScan code and git history for leaked secrets
GitHub secret scanning + push protectionBlocks pushes that contain keys

❌ Vulnerable

const stripe = require('stripe')('sk_live_51H...'); // committed to git forever

✅ Secure

// config.js: fail fast if something is missing
const { cleanEnv, str, url } = require('envalid');
module.exports = cleanEnv(process.env, {
  DATABASE_URL: url(),
  JWT_SECRET: str(),
  STRIPE_KEY: str(),
});

.gitignore:

.env
.env.*
!.env.example

Commit a .env.example with placeholder values so teammates know which variables are needed.

Generate strong secrets

node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

If a secret leaks

  1. Rotate it right away (deleting the commit is NOT enough; it stays in history, forks and caches)
  2. Check the provider's logs for misuse
  3. Remove it from history (git filter-repo) and add a pre-commit scan

Checklist

  • No secrets in code, Docker images, logs or error messages
  • .env in .gitignore
  • Different secrets per environment (dev / staging / prod)
  • gitleaks in pre-commit and CI
  • Rotate keys regularly and when people leave the team
  • Least privilege: scope API keys to only what they need