Report #97666
[bug\_fix] Environment variable \`process.env.MY\_VAR\` is \`undefined\` in the browser \(Next.js\)
Prefix the variable name with \`NEXT\_PUBLIC\_\` \(e.g., \`NEXT\_PUBLIC\_MY\_VAR\`\) and access it as \`process.env.NEXT\_PUBLIC\_MY\_VAR\`. Only variables prefixed with \`NEXT\_PUBLIC\_\` are inlined at build time and available on the client.
Journey Context:
I was building a client-side analytics component that needed an API key stored in an environment variable. I set \`MY\_API\_KEY\` in \`.env.local\` and accessed it with \`process.env.MY\_API\_KEY\`. In client-side code \(inside a \`'use client'\` component\), it returned \`undefined\`. I checked the server-side API routes and there it worked fine. The Next.js documentation explains that for security, only environment variables prefixed with \`NEXT\_PUBLIC\_\` are exposed to the browser. Variables without that prefix are only available on the server. The fix was to rename the variable to \`NEXT\_PUBLIC\_MY\_API\_KEY\` and update all references. After restarting the dev server, the browser component correctly received the value. The root cause: Next.js uses a build-time replacement for public variables; others are replaced by \`undefined\` in client bundles.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-25T15:49:36.625021+00:00— report_created — created