Managing Environment Variables and Secrets in Node.js

Validate at startup, keep server secrets server-side, and never commit a .env file again.
Leaked API keys are one of the most common and most expensive mistakes in web projects. A few habits prevent almost all of them.
Never commit secrets
Add .env and .env.local to .gitignore from the first commit, and keep a .env.example with variable names but no values. If a secret is ever committed, rotate it; deleting the commit is not enough.
Validate at startup
const Env = z.object({
MONGODB_URI: z.string().url(),
JWT_SECRET: z.string().min(32),
STRIPE_SECRET_KEY: z.string().startsWith("sk_"),
});
export const env = Env.parse(process.env);If a variable is missing, the app fails immediately with a clear message instead of breaking on the first request that needs it.
Public vs server-only in Next.js
Anything prefixed with NEXT_PUBLIC_ is bundled into client JavaScript and visible to every visitor. Only public keys belong there, never secret keys.
Different values per environment
- Separate keys for development, staging and production.
- Test-mode payment keys outside production.
- Least-privilege API keys with only the scopes the app needs.
Use the platform's secret store
Hosting platforms and CI systems have encrypted secret storage. Use it instead of copying .env files between machines.









