# Umami Analytics Integration This document describes the Umami analytics integration for the Fotbal Club application. ## Overview Umami is an open-source, privacy-focused web analytics platform integrated into both the backend (Go) and frontend (React/TypeScript). The integration automatically tracks page views and allows custom event tracking throughout the application. ## Features - ✅ **Automatic page view tracking** - Tracks all page visits automatically - ✅ **Custom event tracking** - Track button clicks, form submissions, downloads, etc. - ✅ **Privacy-first** - No cookies, GDPR compliant - ✅ **Admin analytics dashboard** - View comprehensive statistics in the admin panel - ✅ **Auto-initialization** - Automatically creates website tracking in Umami on production deployment - ✅ **Real-time data** - Pull live data from Umami API ## Configuration ### Environment Variables Add the following to your `.env` file: ```env # Umami Analytics UMAMI_URL=https://umami.tdvorak.dev UMAMI_USERNAME=admin UMAMI_PASSWORD=eevRQ6h3G@!c#y4A1T UMAMI_WEBSITE_ID= # Leave empty for auto-create, or set manually after creation ``` ### Initial Setup There are two ways to set up Umami tracking: #### Option 1: Manual Setup 1. Log in to your Umami instance 2. Create a new website manually via the Umami UI 3. Copy the website ID 4. Set `UMAMI_WEBSITE_ID` in your `.env` file #### Option 2: Automatic Setup (Recommended for Production) The system can automatically create a website in Umami when deployed to a real domain: 1. Deploy your application to production 2. Log in to the admin panel 3. The system detects if running on a non-localhost domain 4. Call the initialization endpoint or use the settings page to trigger auto-setup 5. The website is created in Umami and the ID is stored **API Endpoint for Auto-Initialization:** ```bash POST /api/v1/admin/umami/initialize Authorization: Bearer Content-Type: application/json { "name": "Fotbal Club", "domain": "fotbalclub.cz" } ``` Response: ```json { "message": "Umami initialized successfully", "website_id": "7f23c6b1-9b9d-45e3-8a2d-99cabc21e7c0", "script_url": "https://umami.tdvorak.dev/script.js" } ``` ## Architecture ### Backend (Go) **Files:** - `internal/config/config.go` - Umami configuration - `internal/services/umami_service.go` - Umami API client - `internal/controllers/umami_controller.go` - HTTP endpoints - `internal/routes/routes.go` - Route registration **API Endpoints:** Public: - `GET /api/v1/umami/config` - Get Umami configuration for frontend Admin: - `POST /api/v1/admin/umami/initialize` - Initialize Umami tracking - `GET /api/v1/admin/umami/stats?days=30` - Get overview statistics - `GET /api/v1/admin/umami/metrics/:type?days=30` - Get specific metrics **Metric Types:** - `url` - Page views by URL - `referrer` - Traffic sources - `browser` - Browser usage - `os` - Operating system usage - `device` - Device types (desktop/mobile/tablet) - `country` - Visitor countries - `event` - Custom events ### Frontend (React/TypeScript) **Files:** - `frontend/src/hooks/useUmami.ts` - React hook for Umami initialization - `frontend/src/utils/umami.ts` - Event tracking utilities - `frontend/src/pages/admin/AnalyticsAdminPage.tsx` - Analytics dashboard - `frontend/src/App.tsx` - Umami hook integration **Hook Usage:** The Umami script is automatically loaded in `App.tsx`: ```tsx import { useUmami } from './hooks/useUmami'; const App: React.FC = () => { useUmami(); // Initializes Umami tracking // ... rest of app }; ``` ## Event Tracking ### Using Data Attributes (HTML) Add `data-umami-event` attributes to any element: ```tsx // With additional data ``` ### Using JavaScript/TypeScript Import tracking utilities and call them: ```tsx import { trackEvent, trackButtonClick, trackArticleView } from '../utils/umami'; // Generic event trackEvent('Newsletter Subscribe', { source: 'footer' }); // Specific helpers trackButtonClick('Download PDF', '/documents'); trackArticleView(article.id, article.title); trackFormSubmit('Contact Form', true); trackSocialShare('Facebook', url); trackVideoPlay(video.id, video.title); trackSearch(query, resultsCount); trackDownload('brochure.pdf', 'pdf'); trackNewsletterSubscribe('homepage'); trackContactSubmit(true); ``` ### Available Helper Functions All functions are in `frontend/src/utils/umami.ts`: - `trackEvent(name, data?)` - Generic event tracking - `trackButtonClick(button, location?)` - Track button clicks - `trackFormSubmit(form, success?)` - Track form submissions - `trackNavigation(destination, source?)` - Track page navigation - `trackArticleView(id, title)` - Track article views - `trackMatchView(id)` - Track match views - `trackSearch(query, resultsCount?)` - Track search queries - `trackVideoPlay(id, title?)` - Track video plays - `trackNewsletterSubscribe(source?)` - Track newsletter signups - `trackDownload(file, type?)` - Track file downloads - `trackSocialShare(platform, url?)` - Track social shares - `trackContactSubmit(success?)` - Track contact form submissions ## Admin Dashboard Access the analytics dashboard at `/admin/analytika` (admin login required). **Features:** - Overview statistics (pageviews, visitors, visits, bounce rate, average time) - Time range selection (today, 7 days, 30 days, 90 days, 1 year) - Detailed metrics tabs: - Most visited pages - Traffic sources (referrers) - Browser usage - Operating systems - Visitor countries - Device types - Custom events ## Example Integration ### Footer Social Links (Already Integrated) ```tsx // frontend/src/components/layout/Footer.tsx import { trackSocialShare } from '../../utils/umami'; trackSocialShare('Facebook', facebookUrl)} // ... props /> ``` ### Newsletter Subscription ```tsx import { trackNewsletterSubscribe } from '../utils/umami'; const handleSubscribe = async (email: string) => { try { await api.post('/newsletter/subscribe', { email }); trackNewsletterSubscribe('footer-form'); showSuccessToast(); } catch (error) { // handle error } }; ``` ### Article View Tracking ```tsx import { trackArticleView } from '../utils/umami'; useEffect(() => { if (article) { trackArticleView(article.id, article.title); } }, [article]); ``` ## Privacy & GDPR Compliance Umami is privacy-focused by default: - ✅ No cookies used - ✅ No personal data collected - ✅ Anonymized IP addresses - ✅ GDPR compliant out of the box - ✅ Data stored on your own infrastructure ## Testing ### Local Development On localhost, Umami tracking is loaded but may not send data depending on configuration. Use the browser console to verify: ```javascript // Check if Umami is loaded console.log(window.umami); // Manually track an event window.umami?.track('Test Event', { test: true }); ``` ### Production Verification 1. Deploy to production 2. Open browser DevTools > Network tab 3. Filter by "umami" or your Umami domain 4. Navigate the site and trigger events 5. Verify requests are being sent 6. Check the admin dashboard for data ## Troubleshooting ### Script Not Loading - Verify `UMAMI_URL` is correct - Check `UMAMI_WEBSITE_ID` is set - Ensure Umami server is accessible from client browsers - Check browser console for errors ### No Data in Dashboard - Verify tracking script is loaded (check Network tab) - Ensure events are being sent (check Network tab) - Check Umami server logs - Verify correct website ID is being used - Allow a few minutes for data processing ### API Authentication Fails - Verify `UMAMI_USERNAME` and `UMAMI_PASSWORD` are correct - Check Umami server is accessible from backend - Verify API endpoints are correct (may differ by Umami version) ## Security Notes - Never commit real Umami credentials to version control - Use environment variables for all sensitive data - Restrict admin API access to authenticated users only - Consider rate limiting on public tracking endpoints ## Future Enhancements Potential improvements: - **Real-time dashboard updates** - WebSocket/SSE for live stats - **Custom dashboards** - Create custom views for specific metrics - **Goal tracking** - Define and track conversion goals - **A/B testing integration** - Compare variants - **Alerting** - Notifications for traffic spikes or anomalies - **Data export** - Export analytics data for external analysis - **Heatmaps** - Visual representation of user interactions (requires additional tooling) ## Resources - [Umami Official Docs](https://umami.is/docs) - [Umami API Reference](https://umami.is/docs/api) - [Umami GitHub](https://github.com/umami-software/umami)