Build time vs. runtime
NEXT_PUBLIC_ values get replaced with literal strings during `next build`. That's a feature — it's how they end up in the client bundle at all — but it also means they're frozen the moment the build finishes.
Live demo: default vs dynamic rendering
Both cards below print a timestamp. Reload this page a few times.
npm run build && npm start and reload this page there instead.Why this bites teams using one build across environments
If you build a single Docker image and promote it from staging to production, or run next build once in CI and deploy the same output everywhere, every NEXT_PUBLIC_ value is already baked in. Changing an environment variable in your hosting dashboard afterward does nothing until the next build.
import { connection } from 'next/server'
export default async function Page() {
await connection()
// cookies, headers, and other request-time APIs also opt a component
// into dynamic rendering — this line means the read below happens
// per-request, not once at build time.
const value = process.env.MY_VALUE
// ...
}A second, unrelated way to accidentally lose inlining
Next.js only inlines NEXT_PUBLIC_ references it can find with a static analysis pass — a literal process.env.NEXT_PUBLIC_X. Anything computed dynamically is invisible to that pass.
// ✅ inlined at build time
setupAnalytics(process.env.NEXT_PUBLIC_ANALYTICS_ID)
// ❌ NOT inlined — the variable name isn't known until runtime,
// so in the browser this silently resolves to undefined
const key = 'NEXT_PUBLIC_ANALYTICS_ID'
setupAnalytics(process.env[key])- 1Run
npm run build && npm start, load this page, and note both timestamps. Reload several times: the "Default" card should stop changing (or only change on a fresh deploy) while the "Dynamic" card keeps updating. - 2In DevTools → Sources, search the compiled bundle for a NEXT_PUBLIC_ value's literal string — you'll find it hard-coded, which is exactly why it can't change without a rebuild.
- 3If you use Vercel, compare a Preview deployment's environment variables against Production in your project settings — each triggers its own build, so each gets its own frozen values. Covered in more depth in Problem 09.
Changing a NEXT_PUBLIC_ variable in your hosting dashboard updates already-deployed pages immediately.
Calling connection() (or reading cookies/headers) inside a Server Component opts it into per-request rendering.
process.env[someVariableName] gets inlined the same way process.env.NEXT_PUBLIC_X does.