Menu

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

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

DEV Community: javascript·ProofForge·3 days ago
#7FqkjCSG
#devtojavascript#devto#dev#next#undefined
Long article (312 words) — no AI summary yet.
Reading 0:00
15s threshold

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

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

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.