DevOps

Environment Variables Best Practices

Environment variables are the standard way to keep configuration and secrets out of source code, but a few sloppy habits around them are a frequent, avoidable cause of leaked credentials.

Last updated 2026-09-08

1

Never commit .env files containing real secrets

A .env file with real API keys or database credentials, committed even once, remains recoverable from git history indefinitely unless the history is explicitly rewritten. Add .env to .gitignore from the very start of a project.

2

Provide a .env.example with placeholder values

A committed .env.example (with dummy values, not real ones) documents exactly which variables a project needs without exposing any actual secret, making onboarding a new environment straightforward.

3

Validate required environment variables at startup, not lazily at first use

An application that only discovers a missing required variable when a specific code path finally executes fails unpredictably, sometimes well into runtime. Checking all required variables exist at startup fails fast and clearly instead.

4

Never expose server-side secrets to client-side/browser code

In frameworks that distinguish server and client environment variables (like Next.js's NEXT_PUBLIC_ prefix convention), anything without that explicit public marker should never end up in code that ships to the browser, where it becomes visible to anyone.

5

Use different values per environment, never share production secrets into development

Using real production credentials in a local development environment increases the blast radius of any local machine compromise or accidental misconfiguration for no real benefit — use separate, lower-privilege credentials for non-production environments.

Common Mistakes to Avoid

  • Committing a .env file with real secrets to version control, even once
  • No .env.example, leaving new contributors to guess which variables are actually required
  • Discovering a missing required variable only when the relevant code path executes at runtime
  • Accidentally exposing a server-only secret to client-side code
  • Using production credentials in local development instead of separate, scoped-down ones

Frequently Asked Questions

I already committed a secret in a .env file — what now?

Rotate/revoke that credential immediately, treating it as compromised regardless of whether you remove it from git history — the exposure already happened the moment it was pushed, even if you 'delete' it in a later commit.

Is it safe to store secrets in environment variables at all?

It's the standard, widely accepted approach and clearly better than hardcoding secrets in source — for higher-security needs, a dedicated secrets manager (Vault, AWS Secrets Manager) adds encryption at rest and access auditing that plain environment variables don't provide.