Question presented to candidate: "How do environment variables work in Next.js? Which ones reach the browser, when are their values fixed, and how do you avoid leaking a secret?"
What a strong answer should cover:
- Variables load from
process.envand.env*files; the first match wins in this order:process.env,.env.$(NODE_ENV).local,.env.local,.env.$(NODE_ENV),.env. - Only variables prefixed
NEXT_PUBLIC_are available in client code, and they are inlined into the JavaScript at build time. - Server-only variables are read at runtime in dynamically rendered code, but a static page captures their values when it is prerendered at build.
- A server variable read inside a Client Component is not in the browser (undefined), but its server-rendered HTML can contain it.
- Keep secrets in server-only modules; for per-environment public values without rebuilding, read them on the server and pass them down.
Clarifying questions expected:
- "Is the same build promoted across environments?" β then NEXT_PUBLIC_ values are frozen at the first build.
- "Is this value secret?" β then it must never be prefixed or used in a Client Component.
Code / implementation expected: Yes β a server secret, a public value, and passing a runtime value to the client.