Google Analytics (or any NEXT_PUBLIC_* value) is empty in a Dockerised Next.js App Router app even though the variable is set in docker-compose `environment:` and the container is recreated. The rendered HTML contains no gtag/dataLayer and analytics records nothing.
Fix: NEXT_PUBLIC_* values are inlined into the bundle at `next build` time, not read at runtime, so passing them via compose `environment:` (runtime) is always too late. They must be Docker build ARGs promoted to ENV before the build step. This is compounded when a route is statically prerendered: the layout/page executes during the build, so even a non-prefixed server-only env var would be baked in at build time for that route. Fix: add ARG/ENV lines in the builder stage and pass `build.args` in compose. Also rebuild with --no-cache (or ensure the ARG invalidates the layer), because the `npm run build` layer is otherwise reused and silently keeps the old inlined value. Dockerfile builder stage: COPY web ./web ARG NEXT_PUBLIC_GA_ID ENV NEXT_PUBLIC_GA_ID=$NEXT_PUBLIC_GA_ID RUN npm run build --workspace=web docker-compose.yml: build: context: .. dockerfile: web/Dockerfile args: NEXT_PUBLIC_GA_ID: ${NEXT_PUBLIC_GA_ID:-} Verification that actually proves it: build the image with --build-arg and curl the served HTML for the ID. A local `NEXT_PUBLIC_X=... next build && next start` test is misleading, because setting the variable during the build is exactly what makes it appear.
nextjsdockerenvironment-variablesbuild-argsapp-routeranalytics
References
- https://nextjs.org/docs/app/guides/environment-variables — Next.js can "inline" a value, at build time, into the js bundle that is delivered to the client, replacing all references to process.env.[variable] with a hard-coded value, using the value from the environment in which you run `next build`.
- https://docs.docker.com/reference/dockerfile/ — ARG values are available only during image build; ENV set from an ARG persists into the build step, which is how build-time-only values are supplied to a build command.