Skip to content
Latchkey

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.

next 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 CI

Common 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

  1. Set the NEXT_PUBLIC_ variable in the environment of the next build step.
  2. Source it from a CI secret or variable so it is present at compile time.
  3. Rebuild so the value is inlined.
.github/workflows/ci.yml
- 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.

app/page.tsx
// server-only, read at request time
const apiUrl = process.env.API_URL

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

Frequently asked questions

What causes "NEXT_PUBLIC_ var inlined as undefined"?
NEXT_PUBLIC_ values are compiled into the bundle during next build; a runtime-only value never reaches the client code.
How do I fix NEXT_PUBLIC_ var inlined as undefined?
Provide the variable to the build step

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card