Skip to content
Algol Blog

Environment Variables & Secrets in Next.js

— NextJS, Environment Variables, Security, Devops — 2 min read

env-secret-nextjs

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

  1. Never commit .env files containing real values
  2. Use NEXT_PUBLIC_ only for data that is meant to be public
  3. Rotate secrets regularly
  4. Use different values for development, staging, and production
  5. Document every variable in .env.example

5. Things I Avoid

  • Storing secrets in code
  • Using a single .env for 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

© 2026 by Algol Blog. All rights reserved.
Theme by LekoArts