In a Next.js client component you log a variable and get this:
console.log(process.env.NEXT_PUBLIC_API_URL) // undefined
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_URLinstead ofNEXT_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
- Prefix public values with
NEXT_PUBLIC_and reference them literally. - Set the variable on the host and trigger a new build.
- 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
}
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/
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)