Why is process.env.NEXT_PUBLIC_MY_VAR undefined in the browser?
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
console.log(process.env.NEXT_PUBLIC_API_URL) // undefined (client component)Why it happens
- Variable named
API_URLused 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
- Prefix public values with
NEXT_PUBLIC_and reference them literally. - Set the variable on the host and redeploy (rebuild).
- Keep secrets un-prefixed and use 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
}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.
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.