8.7 KiB
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:
# 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
- Log in to your Umami instance
- Create a new website manually via the Umami UI
- Copy the website ID
- Set
UMAMI_WEBSITE_IDin your.envfile
Option 2: Automatic Setup (Recommended for Production)
The system can automatically create a website in Umami when deployed to a real domain:
- Deploy your application to production
- Log in to the admin panel
- The system detects if running on a non-localhost domain
- Call the initialization endpoint or use the settings page to trigger auto-setup
- The website is created in Umami and the ID is stored
API Endpoint for Auto-Initialization:
POST /api/v1/admin/umami/initialize
Authorization: Bearer <admin-token>
Content-Type: application/json
{
"name": "Fotbal Club",
"domain": "fotbalclub.cz"
}
Response:
{
"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 configurationinternal/services/umami_service.go- Umami API clientinternal/controllers/umami_controller.go- HTTP endpointsinternal/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 trackingGET /api/v1/admin/umami/stats?days=30- Get overview statisticsGET /api/v1/admin/umami/metrics/:type?days=30- Get specific metrics
Metric Types:
url- Page views by URLreferrer- Traffic sourcesbrowser- Browser usageos- Operating system usagedevice- Device types (desktop/mobile/tablet)country- Visitor countriesevent- Custom events
Frontend (React/TypeScript)
Files:
frontend/src/hooks/useUmami.ts- React hook for Umami initializationfrontend/src/utils/umami.ts- Event tracking utilitiesfrontend/src/pages/admin/AnalyticsAdminPage.tsx- Analytics dashboardfrontend/src/App.tsx- Umami hook integration
Hook Usage:
The Umami script is automatically loaded in App.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:
<button data-umami-event="Signup button">
Sign up
</button>
// With additional data
<button
data-umami-event="Purchase"
data-umami-event-product="Jersey"
data-umami-event-price="500"
>
Buy Jersey
</button>
Using JavaScript/TypeScript
Import tracking utilities and call them:
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 trackingtrackButtonClick(button, location?)- Track button clickstrackFormSubmit(form, success?)- Track form submissionstrackNavigation(destination, source?)- Track page navigationtrackArticleView(id, title)- Track article viewstrackMatchView(id)- Track match viewstrackSearch(query, resultsCount?)- Track search queriestrackVideoPlay(id, title?)- Track video playstrackNewsletterSubscribe(source?)- Track newsletter signupstrackDownload(file, type?)- Track file downloadstrackSocialShare(platform, url?)- Track social sharestrackContactSubmit(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)
// frontend/src/components/layout/Footer.tsx
import { trackSocialShare } from '../../utils/umami';
<IconButton
href={facebookUrl}
onClick={() => trackSocialShare('Facebook', facebookUrl)}
// ... props
/>
Newsletter Subscription
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
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:
// Check if Umami is loaded
console.log(window.umami);
// Manually track an event
window.umami?.track('Test Event', { test: true });
Production Verification
- Deploy to production
- Open browser DevTools > Network tab
- Filter by "umami" or your Umami domain
- Navigate the site and trigger events
- Verify requests are being sent
- Check the admin dashboard for data
Troubleshooting
Script Not Loading
- Verify
UMAMI_URLis correct - Check
UMAMI_WEBSITE_IDis 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_USERNAMEandUMAMI_PASSWORDare 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)