Next.js NEXT_PUBLIC_ env var undefined because it was missing at build time in CI
Next.js inlines NEXT_PUBLIC_* variables into the client bundle at build time. If the variable is absent when next build runs, it is baked in as undefined, and setting it later at runtime cannot change the already-compiled output.
What this error means
Client code reads process.env.NEXT_PUBLIC_API_URL as undefined in the deployed app, even though the variable is set on the server or container, because it was not present during the CI build.
// browser at runtime
console.log(process.env.NEXT_PUBLIC_API_URL) // undefined
// because NEXT_PUBLIC_API_URL was not set when 'next build' ran in CICommon causes
The variable was set only at runtime, not build time
NEXT_PUBLIC_ values are compiled into the bundle during next build; a runtime-only value never reaches the client code.
The secret was not exposed to the build step
The CI build step did not receive the variable in its environment, so it inlined as undefined.
How to fix it
Provide the variable to the build step
- Set the NEXT_PUBLIC_ variable in the environment of the next build step.
- Source it from a CI secret or variable so it is present at compile time.
- Rebuild so the value is inlined.
- run: npm run build
env:
NEXT_PUBLIC_API_URL: ${{ vars.NEXT_PUBLIC_API_URL }}Read runtime-only config on the server instead
For values that must vary per environment at runtime, read a non-public var in a server component or route, not a NEXT_PUBLIC_ client var.
// server-only, read at request time
const apiUrl = process.env.API_URLHow to prevent it
- Set NEXT_PUBLIC_ variables in the build environment, not just runtime.
- Use server-side env reads for values that must change per environment.
- Document which variables are build-time vs runtime.