Environment Variables and Secrets
Manage environment variables across deployments with proper scoping and security.
EdgeBeginner
Why
Proper env var management prevents secret leaks and enables environment-specific configuration. Cloudflare's edge network spans 330+ cities with sub-50ms p95 latency globally.
Edge functions reduce TTFB by 60-80% compared to origin servers, and Akamai reports 40% of enterprises now use edge compute in 2024.
When
Any project with API keys, database URLs, or environment-specific config. Avoid edge functions for stateful logic requiring database writes — edge runtimes have no persistent connection pool.
Skip if you need long-running tasks (>30s) or heavy CPU computation.
How
# Vercel env vars via CLI
vercel env add DATABASE_URL production
vercel env add STRIPE_SECRET_KEY production
vercel env add NEXT_PUBLIC_API_URL preview production
# .env files (never commit)
.env.local # Local development
.env.development # Development
.env.production # Production
# Next.js env var access
const dbUrl = process.env.DATABASE_URL; // Server-only
const apiUrl = process.env.NEXT_PUBLIC_API_URL; // Client + server
4. Verify deployment — curl -I https://your-app.example.com
5. Monitor logs — check for errors in first 5 minutes
6. Rollback if needed — revert to previous version
Example
# .env.example (committed)
DATABASE_URL=postgresql://user:pass@host:5432/db
STRIPE_SECRET_KEY=sk_live_xxx
NEXT_PUBLIC_API_URL=https://api.example.com
# Verify in production
vercel env ls
vercel env pull .env.vercel --environment=production
Common Problems
- ⚠NEXT_PUBLIC prefix missing — client can't access the var
- ⚠Secret in client bundle — never use non-prefixed vars in client code
- ⚠Configuration drift between environments — use infrastructure-as-code (Terraform/Pulumi) to keep dev/staging/prod identical
Best Practices
- ✓Use .env.example — document required vars without values
- ✓Rotate secrets regularly — use vercel env rm and add
- ✓Set up health checks and graceful shutdown — handle SIGTERM to drain in-flight requests before exit