Next.js public environment values can be embedded into browser JavaScript during the build. Changing only a running server variable may leave visitors using the old bundled value.
IN THIS ARTICLE
Check access and requirements
Classify each setting as private server configuration or deliberately public browser configuration. Identify when the build runs and which environment supplies its values.
01 Build Next.js with the right public environment values
Keep private API credentials and database secrets server-side. Use a public-prefixed variable only when its value may be visible to every visitor.
Supply the intended
NEXT_PUBLIC_values before the production build. Treat public API base URLs and browser analytics identifiers as part of that build’s environment.Read private runtime values from server code through the supported rendering and runtime pattern. Avoid assuming every value used during prerendering remains dynamically replaceable later.
Build one reviewed release and inspect its output for accidental secret exposure. Do not print all environment variables into CI logs.
When a public value changes, rebuild and deploy the affected release, then verify visitors receive the new asset version.
02 Example: correct a stale public endpoint by rebuilding Next.js
Suppose a released browser bundle still calls the staging API after the hosting runtime was changed. The public build value should identify the production endpoint before the next build. This example contains a public address, not an API credential.
NEXT_PUBLIC_API_BASE=https://api.example.com
Supply that value in the build environment, run the reviewed production build, and deploy its complete output. Restarting the previous unchanged build does not rewrite a value already embedded in JavaScript. Keep private tokens in server-only configuration and inspect prerendered HTML as well as browser bundles for accidental exposure.
Expected result: A fresh browser page load makes its request to the production API, and the deployed build identifier matches the reviewed release. If the old address remains, check cached assets and the actual build artifact before changing unrelated application or DNS settings.
Confirm the expected result
Check the browser’s actual outgoing request URL and inspect a new page load. Verify the private server credential does not appear in generated JavaScript, HTML or public configuration responses.
Resolve setup problems
If the old endpoint persists, compare the deployed build identifier, cached assets and build-time configuration. Restarting the same unchanged build cannot rewrite already-inlined values.
A common question
Can I promote one build through several environments?
Only if the settings needed by the browser and prerendered output fit that strategy. Runtime server configuration can vary, while public values already embedded in the build need deliberate handling.