# 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.

> **Scan box (use the site's ScanBox component):** Check whether your live app has this problem. Paste your URL for a free outside-in scan covering exposed keys, open database rules, CORS and security headers. [Scan my app free →](https://proofforge.live/#scan)

## 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

- [Next.js: Environment variables](https://nextjs.org/docs/app/guides/environment-variables)

## Related

- [Fix: secrets in VITE_ / NEXT_PUBLIC_ vars](/fix/vite-env-secrets)
- [Exposed API key checker](/tools/exposed-api-key-checker)
- [Security check for v0 apps](/check/v0)
- [Fix import.meta.env.VITE_… is undefined (Vite)](/errors/vite-env-undefined)
- [All errors](/errors)
