Skip to content

Why is process.env.NEXT_PUBLIC_MY_VAR undefined in the browser?

Short answer

Next.js only sends variables prefixed NEXT_PUBLIC_ to the browser, and it inlines them at build time. If the name lacks the prefix, you read it dynamically (process.env[name]), or the build ran without it, the browser sees undefined. Fix the name and rebuild. Server-only secrets must never get the prefix.

Last updated 2026-11-25 · Reviewed by ProofForge

The exact error

text
console.log(process.env.NEXT_PUBLIC_API_URL) // undefined (client component)

Why it happens

  • Variable named API_URL used in a client component.
  • Dynamic lookup like process.env[key], which isn't inlined.
  • Variable added on the host after the last build.

How to fix it

  1. Prefix public values with NEXT_PUBLIC_ and reference them literally.
  2. Set the variable on the host and redeploy (rebuild).
  3. Keep secrets un-prefixed and use them only in server components, route handlers or server actions.
ts
// 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
}

Check it's fixed

After next build, grep -rn "sk-\|sk_live_\|sb_secret_" .next/static/ returns nothing.

Check your live app

A free, read-only public-surface scan. It cannot diagnose private sessions or every cause described above.

Read-only. No writes or row contents.

FAQ

Is NEXT_PUBLIC_ safe for API keys?

Only for keys designed to be public (Stripe pk_, Supabase publishable, restricted Maps keys). Never for secret keys.

Why does it work in dev but not in production?

Production values are inlined at build time, so the build must see the variable.

Do server components need the prefix?

No. Server code can read any env var.

Sources

Related

Read as Markdown · Scan methodology