Protecting Environment Variables
Protecting Environment Variables
Section titled “Protecting Environment Variables”Introduction
Section titled “Introduction”Environment variables contain secrets — database URLs, API keys, and auth tokens. If they leak, your application and users are at risk.
Risks of Leaked Secrets
Section titled “Risks of Leaked Secrets”| Risk | Consequence |
|---|---|
| Database URL leak | Data breach, data deletion |
| API key leak | Unauthorized API usage, billing charges |
| Auth secret leak | Session forgery, account takeover |
Best Practices
Section titled “Best Practices”Never Commit Secrets
Section titled “Never Commit Secrets”# ✅ Add these to .gitignore.env.local.env.production.env*.local
# ✅ Use .env.example as a template (committed)# .env.exampleDATABASE_URL=postgresql://localhost:5432/mydbNEXTAUTH_SECRET=your-secret-hereUse Environment Variables on Deployment Platforms
Section titled “Use Environment Variables on Deployment Platforms”# Vercel: Project Settings → Environment VariablesDATABASE_URL=postgresql://prod:password@host:5432/dbNEXTAUTH_SECRET=your-production-secret
# Docker: docker-compose.yml or .env fileValidate at Startup
Section titled “Validate at Startup”const required = ['DATABASE_URL', 'NEXTAUTH_SECRET']
for (const key of required) { if (!process.env[key]) { throw new Error(`Missing required env variable: ${key}`) }}Avoid NEXT_PUBLIC_ for Secrets
Section titled “Avoid NEXT_PUBLIC_ for Secrets”// ❌ WRONG — This makes the secret visible in the browserconst apiKey = process.env.NEXT_PUBLIC_STRIPE_SECRET
// ✅ CORRECT — Server-onlyconst apiKey = process.env.STRIPE_SECRETCommon Mistakes
Section titled “Common Mistakes”- Committing
.envfiles to Git — Even if you realize immediately and push a fix, the secret is in the Git history. Rotate the key. - Checking secrets into client code — Anything after
NEXT_PUBLIC_is visible in the browser. Never put server secrets here. - Hardcoding secrets for convenience — “I’ll fix it later” usually means it stays hardcoded forever.
Summary
Section titled “Summary”Protect environment variables by never committing them, using environment-specific files, and validating required variables at startup. Use NEXT_PUBLIC_ only for values that should be visible in the browser.