We use Next.js for our frontend services and want to deploy the same codebase to both preproduction and production. At the moment, separate branches build separate container images because each environment has different `.env` values. Is there a way to build one image and provide the environment-specific configuration at deployment time instead of maintaining two nearly identical images? We currently use `NEXT_PUBLIC_*` variables, which appear to be required when running `next build`, so I'd especially like to know whether a runtime-based approach is possible without major refactoring.
2 Answers
It depends on when the variables are needed. Values used only by the server can be supplied at runtime through the container environment or a mounted configuration file, allowing the same image to be deployed everywhere. However, `NEXT_PUBLIC_*` values are normally embedded into the browser bundle during `next build`, so changing them at runtime is not automatic. You would need to move that configuration behind a server-side endpoint, generate a small runtime configuration file when the container starts, or perform token replacement in the built assets. Otherwise, separate builds are required for different public values.
You shouldn’t need separate branches. Keep one source tree and build the application once, then inject environment-specific settings during deployment wherever possible. For values that truly must be compiled into the client bundle, such as ordinary `NEXT_PUBLIC_*` variables, the build output differs and separate image tags or builds are the straightforward option. You can still reuse Docker cache and common build stages to make those builds fast, or redesign the frontend to fetch environment configuration at startup if using one image is more important than avoiding a small refactor.

We specifically rely on `NEXT_PUBLIC_*` variables, which is why we were assuming separate builds were necessary. A runtime configuration endpoint or startup-generated file may work, but it would require some application changes.