44 lines
1.4 KiB
TypeScript
44 lines
1.4 KiB
TypeScript
import { useEffect } from 'react';
|
|
|
|
const SCRIPT_ELEMENT_ID = 'umami-analytics-script';
|
|
|
|
/**
|
|
* Injects the self-hosted Umami tracking script (see
|
|
* aidlc-docs/features/react-frontend/operations/monitoring/umami-setup.md) when both
|
|
* VITE_UMAMI_SCRIPT_URL and VITE_UMAMI_WEBSITE_ID are configured at build time.
|
|
*
|
|
* Silently does nothing if either variable is missing (e.g. local development, or a
|
|
* build for which the Umami instance/website has not been set up yet) — safe default,
|
|
* no crash on missing config, mirroring the existing Sentry DSN pattern.
|
|
*
|
|
* Skipped during local development (`pnpm dev`) by default so local testing does not
|
|
* pollute production/test visitor analytics.
|
|
*/
|
|
export function UmamiAnalytics() {
|
|
useEffect(() => {
|
|
const scriptUrl = import.meta.env.VITE_UMAMI_SCRIPT_URL;
|
|
const websiteId = import.meta.env.VITE_UMAMI_WEBSITE_ID;
|
|
|
|
if (import.meta.env.DEV || !scriptUrl || !websiteId) {
|
|
return;
|
|
}
|
|
|
|
if (document.getElementById(SCRIPT_ELEMENT_ID)) {
|
|
return;
|
|
}
|
|
|
|
const script = document.createElement('script');
|
|
script.id = SCRIPT_ELEMENT_ID;
|
|
script.src = scriptUrl;
|
|
script.defer = true;
|
|
script.setAttribute('data-website-id', websiteId);
|
|
document.head.appendChild(script);
|
|
|
|
return () => {
|
|
document.getElementById(SCRIPT_ELEMENT_ID)?.remove();
|
|
};
|
|
}, []);
|
|
|
|
return null;
|
|
}
|