From 369de32c2bbfa8fe0426c2d902255284028ecffa Mon Sep 17 00:00:00 2001 From: poli0981 <127664709+poli0981@users.noreply.github.com> Date: Fri, 18 Sep 2026 16:12:41 +0700 Subject: [PATCH] feat(web): Cloudflare Web Analytics beacon from a build variable The cookieless beacon is added to the public page only when the web build has VITE_CF_BEACON_TOKEN (Workers Builds variable; manual site setup with automatic injection off), never to the admin page or the Tauri apps. The site CSP already allows it. Co-Authored-By: Claude Opus 5 --- webapp/vite-plugins/catalog-data.ts | 29 +++++++++++++++++++++++++++++ webapp/vite.config.ts | 8 ++++++-- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/webapp/vite-plugins/catalog-data.ts b/webapp/vite-plugins/catalog-data.ts index 75307cb..9711c90 100644 --- a/webapp/vite-plugins/catalog-data.ts +++ b/webapp/vite-plugins/catalog-data.ts @@ -136,3 +136,32 @@ export function buildInfo(): Plugin { }, } } + +/** + * Cloudflare Web Analytics beacon (cookieless), web build only, and only when + * the build has a token (Workers Builds variable VITE_CF_BEACON_TOKEN; set up + * the site as "manual" with automatic injection off). Never on the admin page, + * whose CSP allows only its own scripts. The site CSP allows the beacon. + */ +export function analyticsBeacon(token: string | undefined): Plugin { + return { + name: 'analytics-beacon', + transformIndexHtml(html, ctx) { + if (!token || !/^[0-9a-f]{32}$/i.test(token) || ctx.path.startsWith('/admin/')) return html + return { + html, + tags: [ + { + tag: 'script', + attrs: { + defer: true, + src: 'https://static.cloudflareinsights.com/beacon.min.js', + 'data-cf-beacon': JSON.stringify({ token }), + }, + injectTo: 'body', + }, + ], + } + }, + } +} diff --git a/webapp/vite.config.ts b/webapp/vite.config.ts index 950f831..d2d2937 100644 --- a/webapp/vite.config.ts +++ b/webapp/vite.config.ts @@ -1,7 +1,7 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import path from 'node:path' -import { buildInfo, catalogData } from './vite-plugins/catalog-data.ts' +import { analyticsBeacon, buildInfo, catalogData } from './vite-plugins/catalog-data.ts' // Set by the Tauri CLI for `tauri dev` / `tauri build`. const isTauri = process.env.TAURI_ENV_PLATFORM !== undefined @@ -11,7 +11,11 @@ export default defineConfig({ // Web: absolute paths (BrowserRouter deep links). Tauri: relative (custom protocol). base: isTauri ? './' : '/', // The Tauri apps read the catalog from the live site, so only the web build bundles it. - plugins: [react(), buildInfo(), ...(isTauri ? [] : [catalogData(repoRoot)])], + plugins: [ + react(), + buildInfo(), + ...(isTauri ? [] : [catalogData(repoRoot), analyticsBeacon(process.env.VITE_CF_BEACON_TOKEN)]), + ], build: { // Web (Cloudflare Workers Builds) and Tauri both build to webapp/dist. outDir: 'dist',