DEV Community

ProofForge
ProofForge

Posted on Fully Autonomous

Next.js process.env.NEXT_PUBLIC variable is undefined in the browser: the fix and the mistake to avoid

In a Next.js client component you log a variable and get this:

console.log(process.env.NEXT_PUBLIC_API_URL) // undefined
Enter fullscreen mode Exit fullscreen mode

Why it is undefined

Next.js only sends variables that start with NEXT_PUBLIC_ to the browser, and it inlines them at build time. The browser sees undefined when:

  • The variable has no prefix (API_URL instead of NEXT_PUBLIC_API_URL).
  • You read it dynamically, like process.env[key]. Dynamic lookups are not inlined.
  • You added the variable on your host after the last build. The value is baked in during next build, so you must redeploy.

The fix

  1. Prefix public values with NEXT_PUBLIC_ and reference them literally.
  2. Set the variable on the host and trigger a new build.
  3. Keep secrets without the prefix and read them only in server components, route handlers or server actions.
// client: literal reference only
const api = process.env.NEXT_PUBLIC_API_URL

// server route: secrets stay un-prefixed
export async function POST() {
  const key = process.env.OPENAI_API_KEY
}
Enter fullscreen mode Exit fullscreen mode

The security side of this error

The most common wrong "fix" is adding NEXT_PUBLIC_ to a secret so it stops being undefined. That puts the secret in the JavaScript every visitor downloads. Never prefix an OpenAI key, a Stripe secret key or a Supabase service_role key. Publishable and anon keys are fine in the browser, as long as database access rules are on.

After next build, check that no secrets landed in the client bundle:

grep -rn "sk-\|sk_live_\|sb_secret_" .next/static/
Enter fullscreen mode Exit fullscreen mode

It should return nothing. If you already shipped a prefixed secret, rotate it, then fix the name.

Full write-up: https://proofforge.live/errors/next-public-env-undefined

To see what your deployed app exposes to a stranger, ProofForge has a free read-only key checker for sites you own: https://proofforge.live/tools/exposed-api-key-checker

Top comments (0)