Environment Variables & Secrets in Next.js
— NextJS, Environment Variables, Security, Devops — 2 min read
Environment Variables & Secrets in Next.js – How I Manage Them
Hi everyone,
Environment variables look trivial, but when mismanaged they can become a source of bugs and even security issues. After getting burned by this a few times, I now have a fairly consistent approach.
1. Separate Them Clearly
I distinguish three types:
- Public variables → safe to expose to the browser (
NEXT_PUBLIC_) - Server-only variables → only accessible on the server
- Secrets → highly sensitive (database URL, API keys, JWT secret)
2. Files I Use
.env.local → development (not committed).env.example → committed template.env.production → production (managed on the hosting platform)I always make sure .env.local is in .gitignore.
3. Validate Environment Variables
I use Zod to validate on app startup:
import { z } from "zod";
const envSchema = z.object({ DATABASE_URL: z.string().url(), NEXTAUTH_SECRET: z.string().min(32), NEXT_PUBLIC_APP_URL: z.string().url(),});
export const env = envSchema.parse(process.env);If anything is missing or malformed, the app fails to start immediately. That's better than hitting an error halfway through.
4. Best Practices I Follow
- Never commit
.envfiles containing real values - Use
NEXT_PUBLIC_only for data that is meant to be public - Rotate secrets regularly
- Use different values for development, staging, and production
- Document every variable in
.env.example
5. Things I Avoid
- Storing secrets in code
- Using a single
.envfor all environments - Forgetting to remove secrets that are no longer used
- Exposing secrets to the client bundle
Conclusion
Managing environment variables well comes down to discipline. Starting with Zod validation and always using .env.example already goes a long way toward preventing many problems.
If your project's env setup is still messy, try adding validation first. The impact is immediate.
A question for you:
How do you manage environment variables right now?
Do you use additional tools like Doppler / Infisical, or is it still manual?
Share in the comments!
— Ady Rahmansyah
Software Engineer | Tech Blogger | Coffee Addict