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 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5 committed 2026-09-18 17:55:02 +07:00
1 parent 6f8b9ed490
commit 369de32c2b
2 files changed
+35 -2

No files matched your search

+29
View File
@@ -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',
},
],
}
},
}
}
+6 -2
View File
@@ -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',