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
| Tool | Use |
|---|---|
dotenv | Load .env in local development (Node 20.6+ also has node --env-file=.env) |
envalid / zod | Validate that the required env vars exist at startup |
| AWS Secrets Manager / GCP Secret Manager / Azure Key Vault | Store secrets in production |
| HashiCorp Vault | Self-hosted secret store, dynamic DB credentials |
gitleaks / trufflehog | Scan code and git history for leaked secrets |
| GitHub secret scanning + push protection | Blocks 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.exampleCommit 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
- Rotate it right away (deleting the commit is NOT enough; it stays in history, forks and caches)
- Check the provider's logs for misuse
- Remove it from history (
git filter-repo) and add a pre-commit scan
Checklist
- No secrets in code, Docker images, logs or error messages
-
.envin.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