From b41d81cce31ac04217619db7fa49f271048325fa Mon Sep 17 00:00:00 2001 From: luen Date: Wed, 4 Nov 2026 12:46:05 +1000 Subject: [PATCH 1/2] Add GA4 page tracking on production Physioshark hosts. Loads gtag (G-VZF5DR37YH) only for data.physioshark.org / physioshark.org, updates CSP, and records SPA navigations. Co-authored-by: Cursor --- AGENTS.md | 2 +- docs/DEPLOY.md | 2 ++ src/app.d.ts | 4 +++ src/lib/components/GoogleAnalytics.svelte | 38 +++++++++++++++++++++++ src/routes/+layout.server.ts | 8 +++-- src/routes/+layout.svelte | 3 ++ vite.config.ts | 16 +++++++--- 7 files changed, 66 insertions(+), 7 deletions(-) create mode 100644 src/lib/components/GoogleAnalytics.svelte diff --git a/AGENTS.md b/AGENTS.md index 5f0464b..6d9b9e9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -188,7 +188,7 @@ REAL_DATA_DIR=data pnpm vitest run src/lib/server/import/realData.test.ts # op ## What not to do - Don't edit, rename, re-save or "clean" the spreadsheets. Don't commit them, fixtures derived from them, or SQLite caches. -- Don't add a chart library or third-party scripts/fonts without updating the CSP in `vite.config.ts` and this file. Map tiles (Esri World Imagery, OpenStreetMap) are the only allowed external images (`img-src`); a new tile host needs the CSP, the e2e tile stub in `e2e/pages.spec.ts` and the attribution. +- Don't add a chart library or third-party scripts/fonts without updating the CSP in `vite.config.ts` and this file. Allowed third parties: GA4 gtag (`www.googletagmanager.com` / `*.google-analytics.com` / `*.analytics.google.com`; Measurement ID `G-VZF5DR37YH`, loaded only on `data.physioshark.org` / `physioshark.org` via `GoogleAnalytics.svelte`) and map tiles (Esri World Imagery, OpenStreetMap — the only external images besides GA beacons; a new tile host needs the CSP, the e2e tile stub in `e2e/pages.spec.ts` and the attribution). - Don't hard-code numbers in page copy; compute them in the load function. - Don't claim causation from the correlations; don't overstate the human-pressure results (the source paper found no significant effect). - Don't reintroduce dual-axis charts or per-point value labels. diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md index 5a954e7..b7beffb 100644 --- a/docs/DEPLOY.md +++ b/docs/DEPLOY.md @@ -28,6 +28,8 @@ The container listens on `127.0.0.1:${HOST_PORT:-8098}` by default. Put it behin Set `ORIGIN` in `.env` to the public URL if the proxy does not send `X-Forwarded-Proto`. +GA4 (`G-VZF5DR37YH`, shared Physioshark stream with physioshark.org) loads only when the request host is `data.physioshark.org` (or `physioshark.org`). Localhost and CI never send hits. Filter reports by **Page hostname** if you need data-site traffic alone. + ## 3. Updating the data - **New or corrected workbook:** copy it into `./data`. The app notices within a minute and rebuilds its cache; no restart needed. Check `/data-quality` afterwards. diff --git a/src/app.d.ts b/src/app.d.ts index 331ae6a..33801d5 100644 --- a/src/app.d.ts +++ b/src/app.d.ts @@ -1,6 +1,10 @@ declare global { /** package.json version, injected by Vite (`define` in vite.config.ts). */ const __APP_VERSION__: string; + interface Window { + dataLayer?: unknown[]; + gtag?: (...args: unknown[]) => void; + } namespace App { // interface Error {} // interface Locals {} diff --git a/src/lib/components/GoogleAnalytics.svelte b/src/lib/components/GoogleAnalytics.svelte new file mode 100644 index 0000000..214f4dc --- /dev/null +++ b/src/lib/components/GoogleAnalytics.svelte @@ -0,0 +1,38 @@ + + + + {#if enabled} + + + {/if} + diff --git a/src/routes/+layout.server.ts b/src/routes/+layout.server.ts index 27babd2..c8c1e9f 100644 --- a/src/routes/+layout.server.ts +++ b/src/routes/+layout.server.ts @@ -1,13 +1,17 @@ import { dataset } from '#lib/server/data'; import type { LayoutServerLoad } from './$types'; -export const load: LayoutServerLoad = () => { +/** Hostnames that load GA4 (Physioshark stream G-VZF5DR37YH). */ +const GA_HOSTS = new Set(['data.physioshark.org', 'physioshark.org']); + +export const load: LayoutServerLoad = ({ url }) => { const d = dataset(); return { importedAt: d.meta.imported_at ?? null, hasData: d.captures.length > 0, seasonRange: d.seasons.length ? [d.seasons[0], d.seasons[d.seasons.length - 1]] : null, external: d.meta.external ? (JSON.parse(d.meta.external) as Record) : {}, - version: d.meta.importer_version ?? '' + version: d.meta.importer_version ?? '', + ga: GA_HOSTS.has(url.hostname) }; }; diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index a8ddc68..f13795e 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -4,6 +4,7 @@ import { page } from '$app/state'; import { NAV } from '#lib/nav'; import { date, season } from '#lib/format'; + import GoogleAnalytics from '#lib/components/GoogleAnalytics.svelte'; import PhysiosharkIcon from '#lib/components/PhysiosharkIcon.svelte'; import type { LayoutProps } from './$types'; @@ -56,6 +57,8 @@ ); + + {title} diff --git a/vite.config.ts b/vite.config.ts index 94f87b2..82518b1 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -20,23 +20,31 @@ export default defineConfig({ }, adapter: adapter({ out: 'build' }), // Per-request nonces for SSR pages; the pre-paint theme script in app.html carries - // %sveltekit.nonce%. No third-party scripts or fonts; map tiles are the only external images. + // %sveltekit.nonce%. Third-party: GA4 (gtag) and map tiles (images only). csp: { mode: 'auto', directives: { 'default-src': ['self'], - 'script-src': ['self'], + 'script-src': ['self', 'https://www.googletagmanager.com'], // Svelte `style:` directives use inline styles. 'style-src': ['self', 'unsafe-inline'], // Map tiles for the interactive maps (#29): Esri imagery and OpenStreetMap. + // GA4 beacons may use image pings. 'img-src': [ 'self', 'data:', 'https://server.arcgisonline.com', - 'https://tile.openstreetmap.org' + 'https://tile.openstreetmap.org', + 'https://www.google-analytics.com', + 'https://www.googletagmanager.com' ], 'font-src': ['self', 'data:'], - 'connect-src': ['self'], + 'connect-src': [ + 'self', + 'https://*.google-analytics.com', + 'https://*.analytics.google.com', + 'https://*.googletagmanager.com' + ], 'object-src': ['none'], 'base-uri': ['self'], 'form-action': ['self'], From 03190d1f0989cc0565ab17d85da3d6ad523f9c1d Mon Sep 17 00:00:00 2001 From: luen Date: Wed, 4 Nov 2026 15:10:31 +1000 Subject: [PATCH 2/2] GA: set up gtag from bundled code, not an inline script The site's CSP only allows SvelteKit's nonce'd inline scripts, so the inline gtag snippet in was blocked on data.physioshark.org: window.gtag never existed and no hits were sent. The command queue is now created in the component (first afterNavigate), before the allowed gtag.js script drains it. Checked on a production build served as data.physioshark.org: the only scripts are SvelteKit's nonce'd ones and gtag.js; on localhost GA isn't loaded. Co-Authored-By: Claude Opus 5.5 --- src/lib/components/GoogleAnalytics.svelte | 29 ++++++++++++++--------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/src/lib/components/GoogleAnalytics.svelte b/src/lib/components/GoogleAnalytics.svelte index 214f4dc..3a9e86e 100644 --- a/src/lib/components/GoogleAnalytics.svelte +++ b/src/lib/components/GoogleAnalytics.svelte @@ -11,10 +11,26 @@ let { enabled }: { enabled: boolean } = $props(); + // The usual inline gtag snippet can't run here: the CSP only lets SvelteKit's own nonce'd + // inline scripts through. So the command queue is set up from this bundled code instead, + // before gtag.js (an allowed external script) arrives and drains it. + function setup() { + if (window.gtag) return; + window.dataLayer = window.dataLayer || []; + window.gtag = function gtag() { + // gtag.js only reads Arguments objects from the queue, not arrays. + window.dataLayer!.push(arguments); + }; + window.gtag('js', new Date()); + window.gtag('config', MEASUREMENT_ID, { send_page_view: false }); + } + + // Runs in the browser only: after hydration and after every client-side navigation. afterNavigate(() => { - if (!enabled || typeof window.gtag !== 'function') return; + if (!enabled) return; + setup(); const url = page.url; - window.gtag('event', 'page_view', { + window.gtag!('event', 'page_view', { page_path: `${url.pathname}${url.search}`, page_location: url.href, page_title: document.title @@ -25,14 +41,5 @@ {#if enabled} - {/if}