feat(analytics): instrument privacy-minimized catalog navigation

This commit is contained in:
Canina Automation committed 2026-10-28 07:59:35 +00:00
1 parent c62d9836e9
commit 13dc74807a
8 files changed
+145 -32

No files matched your search

@@ -1,10 +1,12 @@
'use client';
import { useEffect, useRef } from 'react';
import { useCallback, useEffect, useRef } from 'react';
import { usePathname } from 'next/navigation';
import { analyticsAllowed, catalogRoute, trackCatalogClick } from '../lib/catalogAnalytics';
declare global {
interface Window {
globalPrivacyControl?: boolean;
dataLayer?: any[];
clarity?: any;
gtag?: (...args: any[]) => void;
@@ -20,42 +22,36 @@ interface AnalyticsDeferredProps {
export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsDeferredProps) {
const pathname = usePathname();
const loadedRef = useRef(false);
const initialPathRef = useRef<string | null>(null);
const lastPathRef = useRef<string | null>(null);
const pathnameRef = useRef(pathname);
useEffect(() => { pathnameRef.current = pathname; }, [pathname]);
useEffect(() => {
if (!initialPathRef.current && pathname) {
initialPathRef.current = pathname;
}
}, [pathname]);
const emit = useCallback((event: string, params: Record<string, string>) => {
if (!analyticsAllowed(navigator, window)) return;
if (gaId && window.gtag) window.gtag('event', event, params);
else if (gtmId && window.dataLayer) window.dataLayer.push({ event, ...params });
}, [gaId, gtmId]);
const recordView = useCallback((path: string) => {
if (lastPathRef.current === path) return;
lastPathRef.current = path;
const route = catalogRoute(path);
emit('page_view', { page_path: route, page_location: window.location.origin + route, page_referrer: '' });
if (route === '/shop/[slug]') emit('catalog_product_view', { content_type: 'product' });
if (route === '/blog/[slug]' || route === '/wiki/[slug]') emit('catalog_content_view', { content_type: route.startsWith('/blog') ? 'article' : 'wiki' });
}, [emit]);
// Track client-side page views on Next.js route transitions
useEffect(() => {
if (!pathname || !loadedRef.current) return;
if (pathname === initialPathRef.current) return;
// 1. Google Analytics 4 page_view event on client navigation
if (gaId && typeof window !== 'undefined' && typeof window.gtag === 'function') {
window.gtag('event', 'page_view', {
page_path: pathname,
page_location: window.location.href,
page_title: typeof document !== 'undefined' ? document.title : '',
});
}
// 2. Google Tag Manager page_view event on client navigation
if (gtmId && typeof window !== 'undefined' && Array.isArray(window.dataLayer)) {
window.dataLayer.push({
event: 'page_view',
page_path: pathname,
});
}
}, [pathname, gaId, gtmId]);
recordView(pathname);
}, [pathname, recordView]);
useEffect(() => {
let loaded = false;
const loadAnalytics = () => {
if (loaded) return;
if (loaded || !analyticsAllowed(navigator, window)) return;
loaded = true;
loadedRef.current = true;
@@ -85,7 +81,7 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
}
window.gtag = gtag;
gtag('js', new Date());
gtag('config', gaId, { page_path: window.location.pathname });
gtag('config', gaId, { send_page_view: false, page_title: '', page_location: window.location.origin + catalogRoute(pathnameRef.current || '/'), page_referrer: '' });
// Only append gtag.js script if not already added
if (!document.querySelector(`script[src*="${gaId}"]`)) {
@@ -112,8 +108,16 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
else l.head.appendChild(t);
})(window, document, 'clarity', 'script', clarityId);
}
if (pathnameRef.current) recordView(pathnameRef.current);
};
const onClick = (event: MouseEvent) => {
if (!loadedRef.current || !analyticsAllowed(navigator, window)) return;
const anchor = event.target instanceof Element ? event.target.closest('a') : null;
if (anchor instanceof HTMLAnchorElement) trackCatalogClick(event, anchor, pathnameRef.current || '/', emit);
};
document.addEventListener('click', onClick);
// Listen to first user interaction
window.addEventListener('scroll', loadAnalytics, { passive: true, once: true });
window.addEventListener('touchstart', loadAnalytics, { passive: true, once: true });
@@ -133,6 +137,8 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
return () => {
loaded = true;
loadedRef.current = false;
lastPathRef.current = null;
document.removeEventListener('click', onClick);
clearTimeout(timer);
if (idleId !== undefined) window.cancelIdleCallback(idleId);
window.removeEventListener('scroll', loadAnalytics);
@@ -140,7 +146,7 @@ export default function AnalyticsDeferred({ gtmId, gaId, clarityId }: AnalyticsD
window.removeEventListener('mousemove', loadAnalytics);
window.removeEventListener('keydown', loadAnalytics);
};
}, [gtmId, gaId, clarityId]);
}, [gtmId, gaId, clarityId, emit, recordView]);
return null;
}