Missing Docker Build-Time Env Vars in Nuxt 4 Static Prerendering & Dual CI Smoke Gates
When optimizing Time to First Byte (TTFB) and Core Web Vitals on a content-driven web application, the highest-leverage stack combines dynamic font subsetting, build-time static prerendering, and CDN edge caching. Applying all three simultaneously on inmokang.com eliminated per-request Node.js markdown and SQLite lookups and brought initial document responses down to static-HTML speed.
Immediately after the deployment pipeline turned green (Success), however, a quiet paradox appeared. Pages loaded faster than ever, yet both real-time GA4 sessions and automated HTML telemetry checks flatlined at 0. Every route returned a healthy 200 OK, but the analytics script had vanished completely from the served HTML.
The root cause was an overlooked lifecycle shift: Nuxt had moved rendering from runtime SSR to build-time prerendering, while our multi-stage Dockerfile and GitHub Actions workflow still relied exclusively on runtime ENV injection. This post walks through our three-part latency optimization, dissects the post-purge analytics outage, and details how direct app.head injection, an inline internal-traffic guard, and dual CI HTML smoke gates permanently closed the failure mode.
1. Initial Latency Optimization: Dynamic Font Subsets, Static Prerendering & Edge Caching
The optimization started from a simple question: why re-render infrequently updated blog posts and project write-ups via dynamic SSR on every single visitor request? To fix that, we redesigned inmokang.com's rendering and asset-delivery pipeline across three layers.
First came web font payload reduction. Switching from a monolithic variable font bundle to pretendardvariable-dynamic-subset.css shaved roughly 748KB off initial transfer weight. In @nuxt/fonts, we pinned provider: 'none' for Pretendard Variable and Pretendard and declared only the weights actually rendered (weights: [400, 500, 600]), preventing redundant external provider lookups and unnecessary preload hints.
Second came content-driven static prerendering (PRERENDER_ROUTES). When nuxt.config.ts evaluates, a collectPrerenderContentRoutes() helper scans content/projects/*.md and content/blog/*.md, selecting only routes where status === 'published' and noindex !== true, and registers them under nitro.prerender.routes. Paired with fixed routes such as /about, /privacy, /terms, /rss.xml, and /llms.txt, the build emits complete static HTML documents and feed artifacts ahead of time.
// nuxt.config.ts: Register only published, indexable content routes for static prerendering
const PRERENDER_ROUTES = collectPrerenderContentRoutes()
export default defineNuxtConfig({
css: [
'pretendard/dist/web/variable/pretendardvariable-dynamic-subset.css',
'~/assets/css/main.css',
],
fonts: {
defaults: { weights: [400, 500, 600], styles: ['normal'] },
families: [
{ name: 'Pretendard Variable', provider: 'none' },
{ name: 'Pretendard', provider: 'none' },
{ name: 'JetBrains Mono', preload: false },
],
},
nitro: {
compressPublicAssets: true,
prerender: {
crawlLinks: false,
routes: PRERENDER_ROUTES,
},
},
})
Third came Nitro cache headers paired with Cloudflare edge warmup. Inside server/plugins/seo-headers.ts, clean 200 HTML responses without query strings receive Cache-Control: public, max-age=0, s-maxage=3600, stale-while-revalidate=86400, whereas query-parameterized requests (search !== '') and 4xx/5xx responses are locked down with private, no-cache, no-store and X-Robots-Tag: noindex, nofollow. Right after container rollout, GitHub Actions invokes Cloudflare's purge_everything API and walks key URLs to warm edge PoPs immediately.
| Dimension | Legacy Dynamic SSR Model | Build-Time Prerender + Edge Cache Model |
|---|---|---|
| HTML generation timing | Rendered per request inside the Node.js Nitro server | Pre-generated during npm run build inside docker build |
| Initial font & header cost | Full monolithic font download + per-request SSR CPU | Dynamic subset (~748KB saved) + s-maxage=3600 edge hits |
| Env var evaluation point | Read from docker run -e at container startup | Frozen from process.env during the builder stage |
| Post-deploy cache refresh | Live immediately after container swap | Propagated globally after Cloudflare purge_everything |
With this pipeline in place, both human readers and search crawlers receive prebuilt HTML straight from Cloudflare's edge with near-zero origin load. Yet that exact shift in when HTML gets generated immediately exposed a hidden environment-variable binding trap.
2. Incident Post-Mortem: Why GA4 Sessions Dropped to Zero Right After Cache Purge
The telemetry outage was not caused by a syntax bug—it was caused by a timeline mismatch between Docker's build stage and runtime stage. Under the previous dynamic SSR setup (node ./.output/server/index.mjs), passing -e NUXT_PUBLIC_GTAG_ID=G-XXXXXXXXXX to docker run allowed the running Nitro server to serialize the ID into window.__NUXT__.config.public, after which nuxt-gtag loaded the script during client hydration.
Turning on static prerendering moved HTML generation earlier, into FROM node:20 AS builder inside the Dockerfile. At that point, our builder stage declared no ARG NUXT_PUBLIC_GTAG_ID, and the docker/build-push-action step in .github/workflows/deploy.yml passed zero build-args. We were still faithfully injecting -e NUXT_PUBLIC_GTAG_ID=... only when starting the runtime container.
Consequently, when npm run build iterated through PRERENDER_ROUTES to bake .output/public/.../index.html, process.env.NUXT_PUBLIC_GTAG_ID evaluated to an empty string (""). Compounded by nuxt-gtag either deferring to client hydration or disabling itself on an empty ID, not a single <script async src="https://www.googletagmanager.com/gtag/js?id=..."> tag was baked into the prerendered <head>.
The trigger that surfaced the defect globally was the final Cloudflare purge_everything step in CI. Before the purge, stale edge-cached HTML from the older SSR deployment masked the missing tag. The instant CI flushed the cache and warmed the routes, GA4-stripped static HTML propagated to every edge PoP worldwide.
Tracing the failure chain step by step makes the gap obvious:
- Docker image build stage: Because the
builderstage had noARG, every prerendered HTML document and its serializedruntimeConfig.publicpayload were baked with an empty ID. - Container startup & local health check:
docker run -esupplied the runtime env var, which could not mutate already-baked static files under.output/public/. Meanwhile,curl -fsS http://127.0.0.1:3002/only checked for200 OKand happily passed. - Cloudflare purge & warmup: Flushing the old cache promoted the broken static HTML across the global edge, dropping real-time GA4 sessions and automated HTML verification checks to
0simultaneously.
Key Takeaway: The moment
nitro.prerender.routesis enabled,NUXT_PUBLIC_*values stop behaving like runtime configuration and become build-time constants. Passing the right values viadocker run -ewill never rewrite meta or script tags already baked into.output/public/.
3. Fix Architecture 1: Deterministic SSR <head> Injection & Internal-Traffic Guard
Once the root cause was clear, our first architectural fix changed how the GA4 script enters the document. Relying on a client-side plugin that appends <script> tags only after Vue hydration makes deterministic verification from raw curl responses or static HTML snapshots unnecessarily fragile.
Instead, we disabled duplicate client injection (gtag: { enabled: false }) in nuxt.config.ts and baked the tags directly into the top of <head> via app.head.script whenever IS_PRODUCTION && Boolean(GTAG_ID) holds. A DEFAULT_GTAG_ID fallback and .trim() guard protect against trailing whitespace or unset variables.
// nuxt.config.ts (Masked identifier example)
const DEFAULT_GTAG_ID = 'G-XXXXXXXXXX'
const GTAG_ID = (process.env.NUXT_PUBLIC_GTAG_ID || DEFAULT_GTAG_ID).trim()
const IS_PRODUCTION = process.env.NODE_ENV === 'production'
export default defineNuxtConfig({
app: {
head: {
script: IS_PRODUCTION && Boolean(GTAG_ID)
? [
{
src: `https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(GTAG_ID)}`,
async: true,
tagPosition: 'head',
},
{
innerHTML: `window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}(function(){try{var h=(location.hostname||'').toLowerCase();var q=new URLSearchParams(location.search).get('internal');if(q==='1')localStorage.setItem('inmokang_internal_traffic','1');else if(q==='0')localStorage.removeItem('inmokang_internal_traffic');var internal=q==='1'||(q!=='0'&&localStorage.getItem('inmokang_internal_traffic')==='1');var local=!h||h==='localhost'||h==='127.0.0.1'||h==='0.0.0.0'||h==='::1'||h==='[::1]'||h.endsWith('.localhost')||h.endsWith('.local')||h.endsWith('.internal');if(local||internal){window['ga-disable-${GTAG_ID}']=true;}}catch(e){}})();gtag('js',new Date());gtag('config','${GTAG_ID}');`,
tagPosition: 'head',
},
]
: [],
},
},
gtag: {
enabled: false,
id: GTAG_ID,
},
runtimeConfig: {
public: {
clarityId: process.env.NUXT_PUBLIC_CLARITY_ID || 'YOUR_CLARITY_ID',
gtagId: GTAG_ID,
},
},
})
The critical detail here is the local and internal traffic suppression guard executed immediately before gtag('config', ...). Baking gtag.js straight into prerendered HTML creates a subtle hygiene risk: spinning up a local container (http://127.0.0.1:3002/) for visual QA or repeatedly inspecting production pages could pollute live analytics.
The inline bootstrap script eliminates that risk via two upfront checks:
- Automatic Local & Private-Host Suppression: Requests served from
localhost,127.0.0.1,0.0.0.0,::1, or any.localhost,.local, or.internalhostname immediately setwindow['ga-disable-G-XXXXXXXXXX'] = truebeforegtag('config')fires. - Persistent Operator Opt-Out (
?internal=1): When running QA on the live domain (inmokang.com), visiting once with?internal=1persistsinmokang_internal_traffic = '1'inlocalStorage, excluding all subsequent sessions from that browser. Passing?internal=0clears the flag on demand.
This gives us the best of both worlds: raw prerendered HTML always contains a deterministically verifiable gtag.js tag, while local smoke tests and operator QA visits never contaminate production GA4 metrics.
4. Fix Architecture 2: Multi-Stage Docker ARG Plumbing & Dual CI HTML Smoke Gates
Updating nuxt.config.ts to emit <head> scripts only solves half the problem if the build pipeline never passes those values into the builder stage. To close the loop end to end, we updated both Dockerfile and .github/workflows/deploy.yml with build-time ARG plumbing and dual CI HTML smoke gates.
In Dockerfile, declaring ARG and ENV immediately above RUN npm run build exposes the public analytics identifiers to the Nitro prerenderer, while mirroring the ENV defaults in the node:20-slim runner stage keeps dynamic SSR fallback paths consistent.
# Dockerfile (Condensed & masked)
FROM node:20 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
ARG NUXT_PUBLIC_GTAG_ID=G-XXXXXXXXXX
ENV NUXT_PUBLIC_GTAG_ID=${NUXT_PUBLIC_GTAG_ID}
ARG NUXT_PUBLIC_CLARITY_ID=YOUR_CLARITY_ID
ENV NUXT_PUBLIC_CLARITY_ID=${NUXT_PUBLIC_CLARITY_ID}
RUN npm run build
FROM node:20-slim
WORKDIR /app
ENV NUXT_PUBLIC_GTAG_ID=G-XXXXXXXXXX
ENV NUXT_PUBLIC_CLARITY_ID=YOUR_CLARITY_ID
COPY --from=builder /app/.output ./.output
EXPOSE 3000
CMD ["node", "./.output/server/index.mjs"]
In .github/workflows/deploy.yml, we wired those secrets into build-args and added body-level HTML assertions at two distinct checkpoints: Origin (Gate 1) and CDN Edge (Gate 2).
# .github/workflows/deploy.yml (Core smoke gates excerpt)
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile
push: true
build-args: |
NUXT_PUBLIC_GTAG_ID=${{ secrets.NUXT_PUBLIC_GTAG_ID || 'G-XXXXXXXXXX' }}
NUXT_PUBLIC_CLARITY_ID=${{ secrets.NUXT_PUBLIC_CLARITY_ID || 'YOUR_CLARITY_ID' }}
- name: Deploy to Server via SSH
uses: appleboy/ssh-action@v1.0.3
with:
# Run Gate 1 after container startup and HTTP 200 readiness
script: |
if ! curl -fsS http://127.0.0.1:3002/ | grep -q "${{ secrets.NUXT_PUBLIC_GTAG_ID || 'G-XXXXXXXXXX' }}"; then
echo "ERROR: GA4 tag missing in local SSR HTML"
exit 1
fi
- name: Purge Cloudflare Cache & Edge Warmup
run: |
# Run Gate 2 immediately after Cloudflare purge_everything and route warmup
GTAG_EXPECTED="${{ secrets.NUXT_PUBLIC_GTAG_ID || 'G-XXXXXXXXXX' }}"
if ! curl -fsSL https://inmokang.com/ | grep -q "$GTAG_EXPECTED"; then
echo "::error::GA4 tag (${GTAG_EXPECTED}) missing in live HTML."
exit 1
fi
The deadliest flaw in our previous pipeline was the Silent Green Deploy. A bare curl -fsS http://127.0.0.1:3002/ >/dev/null health check passes as long as the Node process stays alive and returns HTTP 200 OK—letting a build stripped of critical meta or analytics tags sail straight into the Cloudflare purge step and poison the global edge cache.
Separating the two gates isolates both the assertion scope and the blast radius on failure:
| Verification Gate | Execution Point & Target Endpoint | Assertion Condition | Blast-Radius Containment on Failure |
|---|---|---|---|
| Gate 1 (Origin Gate) | Immediately after docker run, before Cloudflare purge (http://127.0.0.1:3002/) | Presence of $GTAG_EXPECTED in the response HTML body | Aborts deployment before CDN purge so existing edge-cached HTML continues shielding live traffic |
| Gate 2 (Edge Gate) | Immediately after Cloudflare purge_everything and warmup (https://inmokang.com/) | Presence of $GTAG_EXPECTED in live HTTPS HTML | Detects edge propagation lag, reverse-proxy cache misconfigurations, or stale edge artifacts before marking CI green |
Placing Gate 1 ahead of the cache purge guarantees that a defective image aborts the workflow while the prior healthy edge cache still serves visitors. Requiring Gate 2 against https://inmokang.com/ after warmup closes the last mile by verifying that origin and CDN edge actually agree before the deploy finishes.
As an added benefit, even when docker/build-push-action uses registry layer caching (cache-from / cache-to), positioning ARG NUXT_PUBLIC_GTAG_ID directly above RUN npm run build guarantees BuildKit automatically invalidates the build layer whenever a secret changes and rebakes every static HTML file with the updated identifier.
Wrapping Up: Keeping Speed Optimizations from Creating Telemetry Blind Spots
Dynamic font subsetting, Nuxt 4 static prerendering, and Cloudflare s-maxage=3600 edge caching deliver dramatic gains in perceived load speed. Without closing the build-time versus runtime gap across both application code and CI/CD, however, it is remarkably easy to ship the fastest version of a site right alongside zero telemetry.
- Reclassify
NUXT_PUBLIC_*as build-time dependencies when enabling prerendering: Once static HTML is baked at build time, public client identifiers must flow through multi-stageDockerfileARGdeclarations and CIbuild-args, not just runtimedocker run -eflags. - Emit critical analytics tags deterministically in static
<head>: Prefer directapp.head.scriptoutput over hydration-only client plugins, paired with an inlinega-disable-*and?internal=1guard so both automated verification and traffic hygiene stay clean. - Assert on HTML body content, never just HTTP
200 OK: Status-code-only checks cannot catch silent regressions; enforce content assertions likegrep -q "$GTAG_EXPECTED"directly in the pipeline. - Bracket CDN cache purges with dual origin/edge smoke gates: Never invoke
purge_everythinguntil Gate 1 passes on local origin (127.0.0.1:3002), and never mark a release green until Gate 2 confirms the live HTTPS edge response (https://inmokang.com/).