Let’s begin from a simple example that illustrates the problem:
Loading code example...
Loading code example...
Loading code example...
If you're building with Next.js, you've likely encountered the
NEXT_PUBLIC_ prefix for environment variables exposed to the browser. The documentation skips the "why" and jumps to the "how." But let's uncover the reasons:Prevents Leaking Sensitive Data
Usual process.env populating by the tools like dotenv can accidentally expose sensitive secrets (like API keys or database passwords) to the client-side JavaScript bundle when reusing them within components. The
NEXT_PUBLIC_ ensures only prefixed variables are included in the browser, keeping your server-side secrets safe.Enforces Explicit Intent
Developers often dump all variables into .env without considering their scope. The
NEXT_PUBLIC_ prefix acts as a guardrail, preventing server-only variables from being misused in client code. It forces you to pause and think:– Why doesn't it work? Oh, it's not for a browser. Should I ever expose it to the browser, or should it stay server-only?
Keep sensitive variables (e.g.,
DB_HOST, API_KEY) without the prefix to restrict them to the server. For client-safe variables, use NEXT_PUBLIC_ and ensure they contain no sensitive data..png?table=block&id=2503641a-bc59-805e-a747-d35c67f5f7f0&cache=v2)
.png?table=block&id=2673641a-bc59-807c-8873-faab835fa519&cache=v2)