Add Matomo analytics tracking with SPA route tracking

This commit is contained in:
2026-01-06 08:50:26 +01:00
parent 799a6b1dea
commit 60a3159996
3 changed files with 56 additions and 0 deletions

View File

@@ -10,8 +10,12 @@ import { Users } from './pages/Users'
import { ChangePassword } from './pages/ChangePassword'
import { PublicQuestionnaire } from './pages/PublicQuestionnaire'
import { NotFound } from './pages/NotFound'
import { useMatomo } from './hooks/useMatomo'
function App() {
// Track page views for Matomo analytics
useMatomo()
return (
<AuthProvider>
<Routes>

39
src/hooks/useMatomo.ts Normal file
View File

@@ -0,0 +1,39 @@
import { useEffect } from 'react'
import { useLocation } from 'react-router-dom'
// Declare Matomo's _paq array on window
declare global {
interface Window {
_paq?: Array<Array<string | number>>
}
}
/**
* Hook to track page views in Matomo for React SPA
* Automatically tracks route changes
*/
export function useMatomo() {
const location = useLocation()
useEffect(() => {
// Track page view when route changes
if (window._paq) {
// Set custom URL (for SPA routing)
window._paq.push(['setCustomUrl', window.location.href])
// Set document title
window._paq.push(['setDocumentTitle', document.title])
// Track the page view
window._paq.push(['trackPageView'])
}
}, [location.pathname, location.search])
}
/**
* Track a custom event in Matomo
*/
export function trackEvent(category: string, action: string, name?: string, value?: number) {
if (window._paq) {
window._paq.push(['trackEvent', category, action, name || '', value || 0])
}
}