file: ./content/docs/api.mdx meta: { "title": "API Reference", "description": "Complete API reference for Databuddy analytics endpoints" } # API Reference Access your analytics data programmatically with Databuddy's REST API. All endpoints require authentication and are rate-limited for security. ## 🔐 Authentication All API requests require authentication using your API key: ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ https://api.databuddy.cc/v1/analytics ``` Get your API key from your [dashboard settings](https://app.databuddy.cc/settings/api). ## 📊 Analytics Endpoints ### Get Website Analytics Retrieve analytics data for a specific website and date range. ```http GET /v1/websites/{website_id}/analytics ``` **Parameters:** * `website_id` (required) - Your website ID * `start_date` (optional) - Start date (ISO 8601) * `end_date` (optional) - End date (ISO 8601) * `granularity` (optional) - Data granularity: `hour`, `day`, `week`, `month` * `metrics` (optional) - Comma-separated metrics to include **Example:** ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.databuddy.cc/v1/websites/web_123/analytics?start_date=2024-01-01&end_date=2024-01-31&granularity=day" ``` **Response:** ```json { "success": true, "data": { "summary": { "pageviews": 15420, "visitors": 8921, "sessions": 12340, "bounce_rate": 0.32, "avg_session_duration": 285.5 }, "events_by_date": [ { "date": "2024-01-01", "pageviews": 512, "visitors": 324, "sessions": 456 } ], "top_pages": [ { "path": "/", "pageviews": 3420, "visitors": 2100 } ], "top_referrers": [ { "referrer": "google.com", "visitors": 1250, "percentage": 15.2 } ], "countries": [ { "country": "United States", "visitors": 4200, "percentage": 28.5 } ], "devices": [ { "device_type": "desktop", "visitors": 5200, "percentage": 35.3 } ], "browsers": [ { "browser_name": "Chrome", "visitors": 6800, "percentage": 46.2 } ] } } ``` ### Get Real-time Analytics
Coming Soon
Get current active visitors and real-time metrics. ```http GET /v1/websites/{website_id}/realtime ``` Real-time analytics with WebSocket streaming will be available soon. ### Get Custom Events Retrieve custom event data and conversions. ```http GET /v1/websites/{website_id}/events ``` **Parameters:** * `event_name` (optional) - Filter by specific event name * `start_date` (optional) - Start date (ISO 8601) * `end_date` (optional) - End date (ISO 8601) **Response:** ```json { "success": true, "data": { "events": [ { "event_name": "signup", "count": 156, "unique_users": 142 }, { "event_name": "purchase", "count": 89, "unique_users": 85 } ], "events_over_time": [ { "date": "2024-01-01", "signup": 12, "purchase": 8 } ] } } ``` ## 🌐 Websites Management ### List Websites Get all websites in your account. ```http GET /v1/websites ``` **Response:** ```json { "success": true, "data": [ { "id": "web_123", "name": "My Website", "domain": "example.com", "created_at": "2024-01-01T00:00:00Z", "verified": true } ] } ``` ### Get Website Details Get details for a specific website. ```http GET /v1/websites/{website_id} ``` **Response:** ```json { "success": true, "data": { "id": "web_123", "name": "My Website", "domain": "example.com", "created_at": "2024-01-01T00:00:00Z", "verified": true, "tracking_code": "db_abc123...", "monthly_pageviews": 45678 } } ``` ## 🤖 AI Assistant ### Query Analytics with AI Use natural language to query your analytics data. ```http POST /v1/websites/{website_id}/assistant/chat ``` **Request:** ```json { "message": "Show me the top pages by pageviews last week", "context": { "dateRange": { "start": "2024-01-01", "end": "2024-01-07" } } } ``` **Response (Streaming):** ```json { "type": "complete", "content": "Here are your top pages by pageviews last week:", "data": { "chart_type": "bar", "results": [ { "path": "/", "pageviews": 1250 }, { "path": "/pricing", "pageviews": 890 } ] } } ``` ## 📝 Event Tracking ### Send Custom Events Track custom events programmatically. ```http POST /v1/track ``` **Request:** ```json { "client_id": "your_tracking_id", "events": [ { "event": "purchase", "properties": { "value": 99.99, "currency": "USD", "product_id": "prod_123" }, "timestamp": "2024-01-01T12:00:00Z" } ] } ``` ## ⚠️ Rate Limits All API endpoints are rate-limited: * **Analytics endpoints**: 100 requests per minute * **Real-time endpoints**: 60 requests per minute * **Event tracking**: 1000 requests per minute Rate limit headers are included in responses: ```http X-RateLimit-Limit: 100 X-RateLimit-Remaining: 95 X-RateLimit-Reset: 1640995200 ``` ## 🚨 Error Handling All errors follow a consistent format: ```json { "success": false, "error": { "code": "INVALID_WEBSITE_ID", "message": "Website not found or access denied", "details": {} } } ``` **Common Error Codes:** * `AUTHENTICATION_FAILED` - Invalid or missing API key * `RATE_LIMIT_EXCEEDED` - Too many requests * `INVALID_WEBSITE_ID` - Website not found or no access * `INVALID_DATE_RANGE` - Invalid start/end dates * `VALIDATION_ERROR` - Request validation failed ## 📚 SDKs and Libraries * **JavaScript/TypeScript**: `@databuddy/sdk` * **Python**: Coming soon * **Go**: Coming soon * **PHP**: Coming soon ## 🔗 Base URLs * **Production**: `https://api.databuddy.cc/v1` * **Sandbox**: `https://api-sandbox.databuddy.cc/v1` file: ./content/docs/dashboard.mdx meta: { "title": "Dashboard Guide", "description": "Complete guide to using your Databuddy analytics dashboard" } import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Callout } from 'fumadocs-ui/components/callout'; import { Card, Cards } from 'fumadocs-ui/components/card'; import { Accordion, Accordions } from 'fumadocs-ui/components/accordion'; # 📊 Dashboard Guide Your Databuddy dashboard provides comprehensive analytics insights with real-time data, detailed reports, and powerful filtering capabilities. **Access**: Visit [app.databuddy.cc](https://app.databuddy.cc) to view your analytics dashboard ## 🏠 Overview Tab The overview tab gives you a high-level view of your website's performance with key metrics and trends. ### 📈 Key Metrics * **Pageviews** - Total page views across your site * **Visitors** - Unique visitors (deduplicated by anonymous ID) * **Sessions** - User sessions with 30-minute timeout * **Bounce Rate** - Percentage of single-page sessions * **Session Duration** - Average time spent per session * **Pages per Session** - Average pages viewed per session * **Load Time** - Average page load time * **TTFB** - Time to First Byte * **Core Web Vitals** - LCP, FCP, CLS when available * **Performance Score** - Overall site performance rating ### ⏰ Time Range Selection Choose from predefined time periods: * **Last 24 hours** - Real-time insights * **Last 7 days** - Weekly trends * **Last 30 days** - Monthly overview * **Last 90 days** - Quarterly analysis Select any date range for specific analysis: * Pick start and end dates * Compare different periods * Analyze specific campaigns or events * Export data for custom ranges **Comparison Mode**: Use the comparison toggle to compare your selected period with the previous period of the same length. ### 📊 Data Granularity View your metrics at different granularities based on your time range: **Best for**: Last 24-48 hours * Detailed hour-by-hour breakdown * Perfect for monitoring recent changes * Real-time performance tracking **Best for**: Weekly/monthly views * Day-by-day analysis * Identify weekly patterns * Track daily performance trends **Best for**: Quarterly views * Week-over-week comparisons * Seasonal trend analysis * Long-term pattern recognition **Best for**: Yearly views * Month-by-month growth tracking * Annual performance reviews * Strategic planning insights ### 📈 Charts and Visualizations **Interactive Metrics Chart:** * 📈 Line charts showing trends over time * 🔍 Toggle different metrics on/off * 🖱️ Interactive hover for detailed values * 📱 Responsive design for mobile viewing **Performance Indicators:** * ✅ Green indicators for positive changes * ⚠️ Red indicators for areas needing attention * 📊 Percentage changes compared to previous period * 🎯 Automatic calculation based on selected time range ## 📄 Top Pages Discover your most popular content and page performance: ### 📊 Page Analytics * **Page path and title** - URL and page title * **Total pageviews** - Number of views * **Unique visitors** - Distinct users * **Average time on page** - Engagement duration * **Bounce rate** - Single-page session rate * **Click to visit** - Click page paths to open them * **Sort by metrics** - Order by any column * **Pagination** - Handle large datasets efficiently * **Search & filter** - Find specific pages quickly ### 💡 Page Insights **Performance Tip**: Pages with high bounce rates but long time-on-page often indicate quality content that doesn't require further navigation. Use this data to: * 🎯 Identify your most valuable content * 🔍 Find pages that need optimization * 📈 Track content performance over time * 🚀 Optimize user journeys ## 🔗 Traffic Sources Understand where your visitors come from and optimize your marketing efforts: ### 📊 Referrer Categories **Source**: Users typing your URL directly or from bookmarks **Characteristics:** * No referrer information * Often returning visitors * High-intent traffic * Brand awareness indicator **Optimization**: Focus on brand building and memorable URLs **Sources**: Google, Bing, DuckDuckGo, and other search engines **Data Shown:** * Search engine names * Organic traffic volume * Search performance trends **Optimization**: SEO improvements and content strategy **Sources**: Facebook, Twitter, LinkedIn, Instagram, etc. **Insights:** * Social platform performance * Content sharing effectiveness * Social engagement tracking **Optimization**: Social media strategy and content tailoring **Sources**: Other websites linking to you **Benefits:** * Referral traffic analysis * Partnership effectiveness * Backlink impact measurement **Optimization**: Relationship building and link acquisition ### 📈 Traffic Analysis For each source, you'll see: * 👥 **Visitor counts** - Number of users from each source * 📊 **Percentage breakdown** - Share of total traffic * 🏷️ **Source classification** - Automatic categorization with icons * 📈 **Trend analysis** - Growth or decline over time ## 🌍 Geographic Analytics Discover your global audience and optimize for different regions: ### 🗺️ Geographic Breakdown **Country-Level Analytics:** * 🏳️ Country names with flag icons * 👥 Visitor counts and percentages * 📊 Interactive sortable data table * 🌍 Geographic distribution insights **Use Cases:** * Identify primary markets * Plan localization efforts * Understand global reach * Optimize content for regions **Detailed Location Data:** * 🏛️ State/province information * 🏙️ City-level analytics (when available) * 🕐 Time zone considerations * 📍 Geographic clustering insights **Benefits:** * Local market analysis * Regional campaign targeting * Time zone optimization * Location-based content strategy **Privacy Note**: Location data is derived from IP addresses and anonymized. No precise location tracking is performed. ## 💻 Technology Stack Analysis Understand your audience's technical environment: ### 📱 Device Analytics **Categories:** * 🖥️ **Desktop** - Traditional computers * 📱 **Mobile** - Smartphones and mobile devices * 📟 **Tablet** - Tablets and large mobile devices **Metrics:** * Visitor distribution * Device-specific performance * User behavior patterns **Data Included:** * 🌐 Browser names and versions * 📊 Market share among your visitors * ⚡ Browser-specific performance data * 🔧 Compatibility insights ### 🖥️ Operating System Insights **Platform Distribution:** * 🍎 **macOS** - Apple computers * 🪟 **Windows** - Microsoft Windows * 🐧 **Linux** - Linux distributions * 📱 **iOS** - Apple mobile devices * 🤖 **Android** - Android devices **Strategic Benefits:** * 🎯 Optimize for popular platforms * 🐛 Debug platform-specific issues * 📊 Understand technical demographics * 🔧 Plan feature compatibility **Cross-Platform Considerations**: Ensure your website works well across all popular platforms used by your audience. ## 🎯 Custom Events Analytics Track and analyze your business-specific events with detailed property breakdowns: ### 📊 Enhanced Event Interface **Tree-Structure Analytics:** * 📊 **Event Level** - Overall event metrics and performance * 📂 **Property Categories** - Organized property groupings with counts * 🔍 **Property Values** - Individual values with percentage distributions * 📈 **Visual Hierarchy** - Color-coded dots and professional typography **Event Display Features:** * 🎯 **Event badges** - Blue dots for main events * 📊 **Count displays** - Total events and unique users * 📈 **Share percentages** - Relative event frequency * 🗓️ **Occurrence tracking** - First and last event timestamps **Automatic Property Analysis:** * 🏷️ **Property extraction** - All custom properties automatically categorized * 📊 **Value distribution** - Percentage breakdown of property values * 🔢 **Count aggregation** - Total occurrences per property value * 📈 **Category sorting** - Properties sorted by frequency **Property Category Features:** * 📂 **Category headers** - Property names with aggregate counts * 📊 **Value lists** - Individual property values with metrics * 🎯 **Usage indicators** - Visual badges showing value counts * 📈 **Percentage pills** - Clean percentage displays **Example Property Structure:** ``` Event: purchase_completed (156 events, 89 users) ├── 📂 product_category (156 values) │ ├── software: 98 (63%) │ ├── hardware: 45 (29%) │ └── services: 13 (8%) ├── 📂 payment_method (156 values) │ ├── credit_card: 124 (79%) │ ├── paypal: 22 (14%) │ └── bank_transfer: 10 (6%) ``` **User Experience Enhancements:** * 🔍 **Individual toggles** - Expand/collapse each property category independently * 📊 **Scrollable content** - Handle large property lists with smooth scrolling * 🎯 **Visual feedback** - Hover effects and transition animations * 📱 **Mobile responsive** - Optimized for all device sizes **Navigation Features:** * ▶️ **Expand arrows** - Rotating chevrons indicate expansion state * 📋 **Value count badges** - Show number of unique values per property * 📊 **Scroll indicators** - Visual cues when content is scrollable * 🎨 **Professional styling** - Subtle gradients and clean borders **Performance Optimizations:** * 🚀 **Lazy rendering** - Only render visible content * 📊 **Efficient scrolling** - Max height limits with overflow handling * 🎯 **State management** - Persistent expand/collapse states * 📱 **Touch optimization** - Mobile-friendly interaction areas ### 🔍 Event Examples ```json { "event": "purchase_completed", "properties": { "product_id": "prod_123", "revenue": 29.99, "currency": "USD", "category": "software" } } ``` ```json { "event": "feature_used", "properties": { "feature": "export_data", "plan": "pro", "usage_count": 5 } } ``` ## ⚡ Real-time Analytics **Coming Soon**: Real-time analytics with WebSocket streaming will be available in the next major update. ### 🔮 Planned Features **Live Metrics Dashboard:** * 👥 **Active visitors** - Users currently on your site * 📄 **Current pageviews** - Real-time page popularity * 🔄 **Live updates** - Data refreshed automatically * 📊 **Real-time charts** - Live data visualization **WebSocket Integration:** * 🚀 **Instant updates** - No page refresh needed * ⚙️ **Configurable intervals** - Customize update frequency * 🟢 **Live indicators** - Visual real-time status * 📱 **Mobile optimized** - Real-time on all devices ## 🔍 Advanced Filtering & Segmentation Slice and dice your data for specific insights: ### 🎛️ Available Filters * 📅 **Date range selection** - Custom time periods * ⏰ **Time of day filtering** - Specific hours * 📆 **Day of week analysis** - Weekday vs weekend patterns * 🗓️ **Month/quarter comparisons** - Seasonal trends * 📱 **Device type filtering** - Mobile, desktop, tablet * 🌍 **Geographic filtering** - Country, region, city * 🔗 **Traffic source filtering** - Direct, search, social, referral * 👥 **Visitor type** - New vs returning (when available) * 📄 **Page path filtering** - Specific pages or sections * 🎯 **Event filtering** - Specific custom events * 🏷️ **Property filtering** - Event property values * 📊 **Performance filtering** - Fast vs slow pages ### 🎯 Segmentation Strategies * **High-engagement users** - Multiple page visits * **Quick browsers** - Short session durations * **Deep readers** - Long time on page * **Mobile-first users** - Primarily mobile traffic * **Performance impact** - Fast vs slow connections * **Browser compatibility** - Modern vs legacy browsers * **Device capabilities** - Screen size and features * **Platform preferences** - Operating system usage ## 📈 Performance Monitoring Monitor your website's technical health and user experience: ### ⚡ Core Web Vitals **Essential Performance Metrics:** **Good**: ≤ 2.5 seconds Measures loading performance. Time until the largest content element is rendered. **Good**: ≤ 100 milliseconds Measures interactivity. Time from first user interaction to browser response. **Good**: ≤ 0.1 Measures visual stability. Sum of all unexpected layout shift scores. **Good**: ≤ 1.8 seconds Time until first content element is rendered on screen. **Optimization Strategies:** **For LCP (Loading):** * 🖼️ Optimize images and videos * 🚀 Use a fast CDN * 📦 Minimize resource load times * 🔄 Implement lazy loading **For FID (Interactivity):** * 📦 Reduce JavaScript bundle size * ⚡ Optimize long-running tasks * 🔄 Use web workers for heavy computation * 📱 Improve mobile responsiveness **For CLS (Visual Stability):** * 📐 Set dimensions for images/videos * 🎨 Avoid inserting content above existing content * 📱 Use transform animations over layout changes * 🔧 Preload web fonts ### 📊 Performance Analytics **Detailed Performance Data:** * 📈 **Load time distribution** - Histogram of page load times * 📄 **Performance by page** - Page-specific metrics * 📅 **Performance trends** - Changes over time * 📱 **Mobile vs desktop** - Device-specific performance **Performance Tip**: Use the performance data to identify slow pages and prioritize optimization efforts where they'll have the biggest impact. ## 🚨 Error Tracking & Debugging Monitor and resolve issues affecting your users: ### 🐛 JavaScript Error Analytics **Comprehensive Error Information:** * 📝 **Error messages** - Descriptive error text * 📍 **Error locations** - File, line, and column numbers * 🔍 **Stack traces** - Detailed execution path * 📊 **Error frequency** - How often errors occur * 👥 **Affected users** - Number of users experiencing errors **Error Types:** * ⚡ **JavaScript errors** - Runtime exceptions * 🔗 **Network errors** - Failed API calls * 📱 **Browser compatibility** - Feature support issues * 🎨 **Resource errors** - Missing images, stylesheets **Resolution Features:** * 🔍 **Error grouping** - Similar errors grouped together * 📈 **Error trends** - Error frequency over time * 🌍 **Error by location** - Geographic error distribution * 📱 **Error by device** - Device-specific error patterns ### 🔧 Error Resolution Workflow 1. **Identify** - Spot errors in the dashboard 2. **Analyze** - Review stack traces and context 3. **Prioritize** - Focus on high-frequency errors 4. **Fix** - Implement solutions 5. **Verify** - Monitor error reduction **Error Impact**: JavaScript errors can significantly impact user experience. Regular monitoring helps maintain site reliability. ## 📱 Mobile Dashboard Experience Access your analytics on any device: ### 📱 Mobile Features **Optimized Mobile Interface:** * 📊 Touch-friendly charts and graphs * 📱 Responsive table layouts * 🔍 Mobile-optimized filtering * ⚡ Fast loading on mobile networks **Mobile-Specific Insights:** * 📱 Mobile vs desktop performance comparison * 🎯 Mobile user behavior patterns * 📊 Mobile-specific error tracking * 🚀 Mobile Core Web Vitals monitoring ## 📊 Data Export & Integration Get your data where you need it: ### 📁 Export Options Download raw data for analysis in spreadsheets or other tools. Programmatic access to your analytics data via REST API. Automated email reports with key metrics and insights. Real-time data streaming to your applications. ## 🎯 Getting the Most from Your Dashboard ### 💡 Best Practices **Regular Monitoring**: Check your dashboard weekly to spot trends and issues early. **Daily Tasks:** * ✅ Check overall visitor trends * 🔍 Monitor error reports * 📈 Review performance metrics * 🎯 Track custom events **Weekly Analysis:** * 📊 Compare week-over-week growth * 🌍 Analyze geographic trends * 📱 Review device usage patterns * 🔗 Evaluate traffic sources **Monthly Reviews:** * 📈 Assess monthly growth trends * 🎯 Review goal achievement * 📄 Analyze top-performing content * 🚀 Plan optimization strategies ## 🆘 Dashboard Troubleshooting ### ❓ Common Issues **Possible Causes:** * 🔧 SDK not properly installed * ⚙️ Tracking disabled in development * 🌐 Domain not verified * 🚫 Ad blockers preventing data collection **Solutions:** * Verify SDK installation * Check browser network tab for requests * Ensure domain verification is complete * Test with ad blockers disabled **Expected Behavior:** * ⏰ Data typically updates within 1-2 minutes * 📊 Some metrics may take up to 5 minutes * 🔄 Refresh the page to see latest data **If data is still delayed:** * Check your internet connection * Verify dashboard status page * Contact support if issues persist **Feature Availability:** * 🎯 Some features require specific tracking to be enabled * 📊 Custom events need manual implementation * ⚡ Performance metrics require opt-in tracking **Enable Missing Features:** * Review your SDK configuration * Enable additional tracking options * Implement custom event tracking ## 🔗 Related Resources Complete SDK configuration and tracking options Implement custom event tracking for business insights Optimize your website's performance metrics Configure privacy and GDPR compliance options **Need Help?** Join our [Discord community](https://discord.gg/JTk7a38tCZ) or [contact support](mailto:support@databuddy.cc) for dashboard assistance. file: ./content/docs/domain-verification.mdx meta: { "title": "Domain Verification", "description": "Secure your analytics with domain verification" } import { Step, Steps } from 'fumadocs-ui/components/steps'; import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Callout } from 'fumadocs-ui/components/callout'; import { Card, Cards } from 'fumadocs-ui/components/card'; import { Accordion, Accordions } from 'fumadocs-ui/components/accordion'; # 🔒 Domain Verification Domain verification ensures that only authorized domains can send analytics data to your Databuddy project. This prevents unauthorized usage and protects your analytics data from spam or malicious traffic. **Required First Step**: You must verify your domain before you can create projects and track analytics data. ## 🛡️ Why Domain Verification? * **Prevent Unauthorized Usage** - Only verified domains can send data * **Protect Against Spam** - Block fake traffic from unverified sources * **Data Integrity** - Ensure analytics come from legitimate sources * **Cost Control** - Prevent unexpected usage charges 1. Add a domain to your Databuddy project 2. Databuddy generates a unique verification token 3. Add a DNS TXT record with the token 4. Databuddy verifies the DNS record 5. Domain is authorized for analytics tracking ## 🚀 Domain Verification Process ## Access Domain Management 1. Go to your [Databuddy Dashboard](https://app.databuddy.cc) 2. Navigate to **Settings** → **Domains** 3. Click **Add Domain** If you don't have an account yet, [sign up for free](https://app.databuddy.cc) first. ## Enter Your Domain Enter your domain name **without** the protocol or paths: ``` ✅ Correct examples: example.com www.example.com app.example.com blog.example.com subdomain.example.com ``` ``` ❌ Avoid these formats: https://example.com (don't include protocol) http://example.com (don't include protocol) example.com/path (don't include paths) example.com:8080 (don't include ports) www.example.com/ (don't include trailing slash) ``` ## Get DNS Instructions After adding your domain, you'll receive: * **DNS Record Name**: `_databuddy.yourdomain.com` * **DNS Record Value**: `databuddy_abc123...` (unique verification token) * **TTL**: 300 seconds (recommended) **Important**: Keep this token secure and don't share it publicly. Generate a new one if it's compromised. ## Configure DNS Record Add a TXT record to your domain's DNS settings: ``` Type: TXT Name: _databuddy Value: databuddy_abc123def456... (your unique token) TTL: 300 ``` For the root domain `example.com`: ``` _databuddy.example.com TXT "databuddy_abc123def456..." ``` For subdomain `app.example.com`: ``` _databuddy.app.example.com TXT "databuddy_abc123def456..." ``` ## Verify Your Domain 1. **Wait for DNS propagation** (15-30 minutes typical) 2. **Return to your Databuddy dashboard** 3. **Click "Verify"** next to your domain 4. **Check status** - should change from "Pending" to "Verified" Once verified, you can create projects and start tracking analytics for this domain! ## 🌐 DNS Provider Instructions Choose your DNS provider for specific setup instructions: **Step-by-step setup:** 1. **Log in** to [Cloudflare Dashboard](https://dash.cloudflare.com) 2. **Select your domain** from the list 3. **Go to DNS** → **Records** 4. **Click "Add record"** 5. **Configure the record:** * **Type**: `TXT` * **Name**: `_databuddy` * **Content**: Your verification token * **Proxy status**: 🔘 DNS only (gray cloud) - **Important!** * **TTL**: Auto 6. **Save** the record **Critical**: Make sure the proxy status is set to "DNS only" (gray cloud). Orange cloud will prevent verification. **Verification time**: Usually 5-15 minutes **Step-by-step setup:** 1. **Log in** to [Namecheap Account](https://www.namecheap.com/myaccount/) 2. **Go to Domain List** → **Manage** (next to your domain) 3. **Click "Advanced DNS"** tab 4. **Click "Add New Record"** 5. **Configure the record:** * **Type**: `TXT Record` * **Host**: `_databuddy` * **Value**: Your verification token * **TTL**: `Automatic` 6. **Save changes** **Verification time**: Usually 10-30 minutes **Step-by-step setup:** 1. **Log in** to [GoDaddy Account](https://account.godaddy.com/) 2. **Go to My Products** → **DNS** 3. **Find your domain** and click **DNS** button 4. **Click "Add"** in the Records section 5. **Configure the record:** * **Type**: `TXT` * **Name**: `_databuddy` * **Value**: Your verification token * **TTL**: `1 Hour` 6. **Save** the record **Verification time**: Usually 15-60 minutes **Step-by-step setup:** 1. **Open** [Route 53 Console](https://console.aws.amazon.com/route53/) 2. **Go to Hosted zones** 3. **Select your domain** 4. **Click "Create record"** 5. **Configure the record:** * **Record name**: `_databuddy` * **Record type**: `TXT` * **Value**: Your verification token (with quotes) * **TTL**: `300` 6. **Click "Create records"** **Verification time**: Usually 5-15 minutes **Step-by-step setup:** 1. **Log in** to [Google Domains](https://domains.google.com/) 2. **Select your domain** 3. **Go to DNS** tab 4. **Scroll to Custom records** 5. **Add a new record:** * **Host name**: `_databuddy` * **Type**: `TXT` * **TTL**: `300` * **Data**: Your verification token 6. **Save** the record **Verification time**: Usually 10-30 minutes **General instructions for any DNS provider:** 1. **Access your DNS management panel** 2. **Add a new TXT record** with these settings: * **Name/Host**: `_databuddy` * **Type**: `TXT` * **Value/Content**: Your verification token * **TTL**: `300` or `5 minutes` 3. **Save the record** **Common DNS interfaces:** * Look for "DNS Records", "DNS Management", or "Zone File" * Some providers use "Host" instead of "Name" * Some providers use "Content" instead of "Value" ## 🔍 Verification Status ### Understanding Statuses Domain is added but not yet verified. DNS record needs to be configured. Domain is verified and ready to track analytics. You can create projects for this domain. Verification failed. Check DNS configuration and try again. Domain was automatically verified (company email match or whitelist). ### Automatic Verification Some domains are automatically verified: **Auto-verification criteria:** * Your registered email domain matches the domain you're verifying * You're part of a pre-approved organization * Domain is whitelisted for testing purposes ## 🔧 Troubleshooting ### Common Verification Issues **Possible causes:** * DNS record hasn't been added yet * Incorrect record name (should be `_databuddy`) * Wrong record type (should be `TXT`) * DNS changes haven't propagated **Solutions:** 1. ✅ **Double-check record name**: Must be exactly `_databuddy` 2. ✅ **Verify record type**: Must be `TXT` record 3. ✅ **Wait for propagation**: Can take up to 48 hours 4. ✅ **Test DNS**: Use [DNS Checker](https://dnschecker.org/) to verify **Possible causes:** * Token copied incorrectly * Extra spaces or hidden characters * Token expired or regenerated **Solutions:** 1. ✅ **Regenerate token**: Get a fresh verification token 2. ✅ **Copy carefully**: Ensure no extra spaces or characters 3. ✅ **Use quotes**: Some DNS providers require quotes around the value 4. ✅ **Re-add record**: Delete old record and add new one with correct token **Possible causes:** * Cloudflare proxy enabled (orange cloud) * Multiple conflicting TXT records * DNS caching issues * Record not fully propagated **Solutions:** 1. ✅ **Disable Cloudflare proxy**: Set to "DNS only" (gray cloud) 2. ✅ **Remove duplicates**: Delete any duplicate TXT records 3. ✅ **Clear cache**: Wait 24 hours or flush DNS cache 4. ✅ **Check globally**: Use DNS propagation checker tools **Possible causes:** * Including `http://` or `https://` * Including paths like `/path` * Including ports like `:8080` * Using IP addresses instead of domains **Solutions:** 1. ✅ **Use domain only**: `example.com` not `https://example.com` 2. ✅ **No paths**: `example.com` not `example.com/app` 3. ✅ **No ports**: `example.com` not `example.com:3000` 4. ✅ **Use domains**: Not IP addresses like `192.168.1.1` ### DNS Propagation Tools Check if your DNS record is visible globally: Check DNS propagation from multiple locations worldwide Global DNS propagation checker with visual map Google's DNS lookup tool for technical analysis ### Manual DNS Check You can also check DNS records manually: ```bash # Check TXT record (Linux/Mac) dig TXT _databuddy.example.com # Alternative command nslookup -type=TXT _databuddy.example.com # Expected output should show your verification token ``` ```powershell # Check TXT record (Windows) Resolve-DnsName -Name "_databuddy.example.com" -Type TXT # Alternative command nslookup -type=TXT _databuddy.example.com # Expected output should show your verification token ``` ## 📚 Advanced Configuration ### Multiple Domains You can verify multiple domains for a single project: **Use cases for multiple domains:** * Different environments: `staging.example.com`, `app.example.com` * Multiple brands under one organization * International domains: `example.com`, `example.co.uk` **Each domain needs its own verification:** 1. Add each domain separately 2. Get unique verification token for each 3. Configure DNS record for each domain 4. Verify each domain individually ### Subdomain Considerations **Root domain vs subdomain verification:** * **Root domain** (`example.com`): Covers `www.example.com` automatically * **Subdomain** (`app.example.com`): Only covers that specific subdomain * **Wildcard**: Not currently supported **Important**: If you use subdomains, verify each one separately. Verifying `example.com` does NOT automatically verify `app.example.com`. ### Security Best Practices * Don't share verification tokens publicly * Regenerate tokens if compromised * Store tokens securely if needed for automation * Use DNSSEC if your provider supports it * Monitor DNS records for unauthorized changes * Keep DNS provider account secure with 2FA ## ❓ Still Having Issues? If you're still having trouble with domain verification: Get real-time help from our community and team Contact our support team directly Continue with the getting started guide once verified **Next Steps**: Once your domain is verified, you can [create your first project](/docs/getting-started) and start tracking analytics! file: ./content/docs/getting-started.mdx meta: { "title": "Getting Started", "description": "Install and configure Databuddy for your application" } import { Step, Steps } from 'fumadocs-ui/components/steps'; import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Callout } from 'fumadocs-ui/components/callout'; import { Card, Cards } from 'fumadocs-ui/components/card'; # Getting Started with Databuddy This guide will help you set up Databuddy analytics in your application in just a few minutes. **Prerequisites**: You'll need a verified domain before you can create a project. [Verify your domain first](/docs/domain-verification) if you haven't already. ## Create Your Account 1. Go to [app.databuddy.cc](https://app.databuddy.cc) 2. Sign up for a free account 3. Create your first project with your verified domain 4. Copy your **Client ID** from the dashboard Make sure your domain is verified before creating a project. Unverified domains cannot track analytics data. ## Install the SDK Choose your installation method based on your application type: Install the official Databuddy SDK: ```bash # Using bun (recommended) bun add @databuddy/sdk # Using npm npm install @databuddy/sdk # Using yarn yarn add @databuddy/sdk ``` For any website, use the script tag method: ```html ``` ## Configure Tracking Add the `` component to your root layout: ```tsx title="app/layout.tsx" import { Databuddy } from '@databuddy/sdk'; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` **Environment Variables:** ```bash title=".env.local" NEXT_PUBLIC_DATABUDDY_CLIENT_ID=your-client-id-here ``` Add the script to your HTML before the closing `` tag: ```html title="index.html" My Website ``` ## Verify Installation Check that analytics are working correctly: 1. **Visit your website** in a new browser tab 2. **Open your Databuddy dashboard** at [app.databuddy.cc](https://app.databuddy.cc) 3. **Check Real-time data** - you should see yourself as an active visitor 4. **Navigate between pages** - verify page views are being recorded If you see real-time data in your dashboard, congratulations! Databuddy is now tracking your website analytics. ## ⚙️ Configuration Options ### Essential Settings ```tsx title="Recommended Configuration" ``` ```html title="Recommended Configuration" **Security**: All tracking scripts automatically include `crossorigin="anonymous"` for enhanced security. ``` ### Environment-Specific Setup **Best Practice**: Disable tracking in development to avoid polluting your analytics with test data. ```tsx title="Environment Configuration" const isDevelopment = process.env.NODE_ENV === 'development'; const isProduction = process.env.NODE_ENV === 'production'; ``` ## 🎯 Custom Event Tracking Track custom events with rich properties for comprehensive analytics: ```tsx title="Custom Events with Rich Properties" import { useEffect } from 'react'; function SignupForm() { const handleSignup = (plan: string) => { // Track conversion event with detailed context window.databuddy?.track('signup_completed', { source: 'landing_page', plan: plan, trial_days: plan === 'pro' ? 14 : 7, form_type: 'inline', utm_source: new URLSearchParams(window.location.search).get('utm_source'), referrer_domain: document.referrer ? new URL(document.referrer).hostname : null }); }; const handleFormInteraction = (fieldName: string) => { // Track form engagement window.databuddy?.track('form_field_focused', { form_type: 'signup', field_name: fieldName, page: window.location.pathname, user_agent_mobile: /Mobile|Android/i.test(navigator.userAgent) }); }; useEffect(() => { // Track form view with context window.databuddy?.track('signup_form_viewed', { page: window.location.pathname, form_position: 'hero_section', visit_source: document.referrer || 'direct', viewport_width: window.innerWidth }); }, []); return (
handleSignup('free')}> handleFormInteraction('email')} placeholder="Enter your email" />
); } ```
```html title="Custom Events with Detailed Properties" ```
**Property Analytics**: Your custom event properties are automatically analyzed in the dashboard with expandable breakdowns, showing property distributions and value percentages in an interactive tree structure. ## 🎉 What's Next? Explore all configuration options and advanced features Learn to navigate your analytics dashboard Set up custom events, performance monitoring, and more Configure privacy settings and GDPR compliance ## 🆘 Troubleshooting **Not seeing data in your dashboard?** 1. **Check your Client ID** - Make sure it matches your project 2. **Verify your domain** - Ensure your domain is verified in the dashboard 3. **Test manually** - Try `db.track('test', {})` in your browser console 4. **Check Network tab** - Look for requests to `basket.databuddy.cc` 5. **Review environment** - Make sure tracking isn't disabled in production Need help? Join our [Discord community](https://discord.gg/JTk7a38tCZ) or [contact support](mailto:support@databuddy.cc). file: ./content/docs/index.mdx meta: { "title": "What is Databuddy", "description": "Privacy-first web analytics. 247x faster than Google Analytics, GDPR compliant by default, no cookies required." } import { Card, Cards } from 'fumadocs-ui/components/card'; import { Callout } from 'fumadocs-ui/components/callout'; Databuddy provides powerful website analytics while respecting user privacy. Get comprehensive insights without cookies, consent banners, or GDPR headaches. **247x faster** than Google Analytics • **No cookies required** • **GDPR compliant by default** ## Why Choose Databuddy? Only 3KB script size. Improve your Core Web Vitals and SEO rankings instantly. Anonymous analytics with no personal data collection. No consent banners needed. Live dashboards with 100% accurate data. No sampling, no delays. Works with React, Next.js, WordPress, Shopify. Install in minutes. ## Analytics Features **Essential Tracking** * Page views with automatic SPA routing * Anonymous user sessions * Traffic sources and referrers * Real-time visitor monitoring **Performance Monitoring** * Core Web Vitals (LCP, FID, CLS) * Page load timing metrics * JavaScript error tracking * Custom business events **E-commerce Analytics** * Purchase tracking and revenue * Shopping cart behavior * Product performance metrics * Conversion funnel analysis ## Quick Start Guide Sign up free and verify your domain Add script tag or install React package Watch real-time data in your dashboard ## Platform Integrations TypeScript support with React hooks and components App Router and Pages Router with automatic route tracking Plugin installation and manual setup options E-commerce tracking with purchase analytics ## Key Benefits **No Cookies Required**\ Uses localStorage for anonymous session tracking only. No cookie banners needed. **GDPR Compliant by Default**\ Anonymous data collection means automatic compliance. No consent management required. **Developer-Friendly**\ TypeScript support, React components, comprehensive API, detailed documentation. **Cross-Platform**\ Works on websites, web apps, mobile apps, any JavaScript environment. ## Pricing **Free tier: 10,000 monthly page views** - Perfect for personal projects and small websites **Early adopters get 3 months free, unlimited websites and page views** ## Get Support * [Complete Documentation](/docs/getting-started) - Guides and API reference * [Email Support](mailto:help@databuddy.cc) - Direct help from our team * [GitHub Issues](https://github.com/databuddy/issues) - Bug reports and features *** Ready to get started? [Create your free account](https://app.databuddy.cc) or [read the documentation](/docs/getting-started). file: ./content/docs/sdk.mdx meta: { "title": "SDK Reference", "description": "Complete reference for the Databuddy SDK and JavaScript library" } import { Tab, Tabs } from 'fumadocs-ui/components/tabs'; import { Callout } from 'fumadocs-ui/components/callout'; import { Card, Cards } from 'fumadocs-ui/components/card'; import { Accordion, Accordions } from 'fumadocs-ui/components/accordion'; # 📦 SDK Reference The Databuddy SDK provides both a React component and a standalone JavaScript library for tracking analytics events. This guide covers all configuration options, types, and usage patterns based on the actual implementation. **Version**: 1.0.2 | **API**: basket.databuddy.cc | **CDN**: app.databuddy.cc ## 🚀 Installation ```bash # Using bun (recommended) bun add @databuddy/sdk # Using npm npm install @databuddy/sdk # Using yarn yarn add @databuddy/sdk ``` No installation needed - load directly from CDN: ```html ``` ## ⚡ Quick Start ```tsx title="app/layout.tsx" import { Databuddy } from '@databuddy/sdk'; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` ```html title="index.html" My Website ``` ## 🔧 Configuration Options ### Required Settings ```tsx ``` ```html ``` ### Core Tracking Features These features are **enabled by default** and recommended for most websites: Tracks page views and route changes in SPAs. ```tsx ``` ```html ``` **Events tracked**: `screen_view`, `page_view` Monitors page load times, navigation timing, and resource performance. ```tsx ``` ```html ``` **Events tracked**: `performance_navigation`, `performance_resource` Tracks user sessions with a 30-minute timeout using sessionStorage. ```tsx ``` ```html ``` **Events tracked**: `session_start`, session duration metrics ### Optional Tracking Features These features are **disabled by default** - enable as needed: **Performance Impact**: Enabling many optional features can increase data volume and impact performance. Choose only what you need. Tracks Core Web Vitals: LCP, FID, CLS, TTFB, INP. ```tsx // ⚠️ Can generate significant data volume trackWebVitals={true} ``` **Events tracked**: `web_vitals` with metrics data Captures JavaScript errors and unhandled promise rejections. ```tsx trackErrors={true} ``` **Events tracked**: `javascript_error`, `unhandled_rejection` Tracks clicks on external links. ```tsx trackOutgoingLinks={true} ``` **Events tracked**: `outgoing_link_click` Measures how far users scroll (25%, 50%, 75%, 100% milestones). ```tsx trackScrollDepth={true} ``` **Events tracked**: `scroll_depth` Tracks time on page and user interactions. ```tsx trackEngagement={true} ``` **Events tracked**: `engagement_time`, `page_engagement` ```tsx // Advanced tracking options trackExitIntent={false} // Mouse leave detection trackInteractions={false} // Clicks, keypresses trackBounceRate={false} // Single-page visits trackHashChanges={false} // URL hash changes trackAttributes={false} // data-* attributes on clicks ``` ### Performance & Reliability ```tsx title="Performance Configuration" ``` ```html title="Performance Configuration" ``` **Batching**: Groups multiple events into single requests. Enable for high-traffic sites to reduce server load. ### Advanced Configuration Only change these if you're self-hosting Databuddy: ```tsx ``` Filter events before they're sent: ```tsx { // Don't track admin pages if (event.properties?.page?.includes('/admin')) { return false; } // Don't track bot traffic if (navigator.userAgent.includes('bot')) { return false; } return true; }} /> ``` Complete TypeScript definition: ```tsx interface DatabuddyConfig { // Required clientId: string; // Optional authentication (server-side only) clientSecret?: string; // Endpoints apiUrl?: string; // Default: 'https://basket.databuddy.cc' scriptUrl?: string; // Default: 'https://app.databuddy.cc/databuddy.js' // SDK metadata sdk?: string; // Default: 'web' sdkVersion?: string; // Default: '1.0.2' // Control disabled?: boolean; // Default: false // Core tracking (enabled by default) trackScreenViews?: boolean; // Default: true trackPerformance?: boolean; // Default: true trackSessions?: boolean; // Default: true // Optional tracking (disabled by default) trackWebVitals?: boolean; // Default: false trackErrors?: boolean; // Default: false trackOutgoingLinks?: boolean; // Default: false trackScrollDepth?: boolean; // Default: false trackEngagement?: boolean; // Default: false trackExitIntent?: boolean; // Default: false trackInteractions?: boolean; // Default: false trackBounceRate?: boolean; // Default: false trackHashChanges?: boolean; // Default: false trackAttributes?: boolean; // Default: false // Performance & reliability samplingRate?: number; // Default: 1.0 (0.0-1.0) enableRetries?: boolean; // Default: true maxRetries?: number; // Default: 3 initialRetryDelay?: number; // Default: 500ms (50-10000) enableBatching?: boolean; // Default: false batchSize?: number; // Default: 10 (1-50) batchTimeout?: number; // Default: 2000ms (100-30000) // Custom filter function filter?: (event: any) => boolean; } ``` ## 🎯 Custom Event Tracking Track custom business events with detailed properties for comprehensive analytics: ```tsx title="Custom Events with Properties" import { useEffect } from 'react'; function ProductPage({ product }: { product: Product }) { useEffect(() => { // Track product view with detailed properties window.databuddy?.track('product_viewed', { product_id: product.id, product_name: product.name, category: product.category, price: product.price, currency: 'USD', brand: product.brand, in_stock: product.availability > 0 }); }, [product]); const handlePurchase = () => { // Track conversion with purchase details window.databuddy?.track('purchase_completed', { product_id: product.id, revenue: product.price, currency: 'USD', payment_method: 'credit_card', shipping_method: 'standard', coupon_used: false }); }; const handleAddToCart = (quantity: number) => { // Track cart actions with context window.databuddy?.track('add_to_cart', { product_id: product.id, quantity: quantity, value: product.price * quantity, currency: 'USD', source: 'product_page' }); }; return (

{product.name}

); } ``` **Alternative Object Syntax:** ```tsx // Both syntaxes work identically db.track('event_name', { key: 'value' }); window.databuddy?.track('event_name', { key: 'value' }); ```
```html title="Custom Events with Rich Properties" ```
### Custom Event Best Practices **Event Naming**: Use snake\_case for event names (e.g., `signup_completed`, `product_viewed`) **Properties**: Include rich context for detailed analytics but avoid PII (personally identifiable information) **Property Keys**: Use consistent naming across events for better analysis ```tsx // ✅ Detailed properties for comprehensive analysis db.track('purchase_completed', { product_category: 'software', // Groupable property payment_method: 'credit_card', // Behavior analysis plan_type: 'annual', // Business metric discount_applied: true, // Conversion tracking value: 299.99, // Revenue tracking currency: 'USD', // Standardization source: 'pricing_page' // Attribution }); // ✅ Consistent property names across events db.track('add_to_cart', { product_category: 'software', // Same key as purchase value: 299.99, // Same key format currency: 'USD', // Consistent currency source: 'product_page' // Consistent attribution }); ``` ```tsx // ❌ Don't include PII db.track('signup', { email: 'user@example.com', // PII violation phone: '+1234567890', // PII violation ip_address: '192.168.1.1' // PII violation }); // ❌ Don't use inconsistent naming db.track('purchase', { productCat: 'software', // camelCase instead of snake_case 'payment method': 'card', // spaces in keys Price: 299.99 // inconsistent capitalization }); // ❌ Don't use vague event names db.track('click'); // Too generic db.track('User Action'); // Spaces + vague ``` ### 📊 Property Breakdown Analytics Your custom event properties are automatically analyzed in the dashboard with: **Automatic Property Analysis:** * 🏷️ **Property keys** - All custom properties are extracted and categorized * 📊 **Value distributions** - See how property values are distributed * 🎯 **Usage frequency** - Track which properties appear most often * 📈 **Trend analysis** - Monitor how property values change over time **Example Dashboard View:** ``` Event: purchase_completed (247 events) ├── 📂 product_category (247 values) │ ├── software: 156 (63%) │ ├── hardware: 78 (32%) │ └── services: 13 (5%) ├── 📂 payment_method (247 values) │ ├── credit_card: 198 (80%) │ ├── paypal: 35 (14%) │ └── bank_transfer: 14 (6%) └── 📂 plan_type (247 values) ├── annual: 186 (75%) └── monthly: 61 (25%) ``` **Dashboard Features:** * 🔍 **Expandable categories** - Click to explore property breakdowns * 📊 **Scrollable lists** - Handle large property value lists efficiently * 🎯 **Individual toggles** - Open/close each property category independently * 📈 **Percentage calculations** - Automatic percentage distribution * 🔢 **Value counts** - Total occurrences for each property value **Visual Hierarchy:** * **Event Level** - Overall event metrics and counts * **Property Level** - Property categories with aggregate counts * **Value Level** - Individual property values with percentages ## 📋 Configuration Reference ### Default Values Table | Option | Default | Type | Range | | -------------------- | --------------------------------------- | --------- | ------------ | | `clientId` | - | `string` | **Required** | | `disabled` | `false` | `boolean` | - | | `trackScreenViews` | `true` | `boolean` | - | | `trackPerformance` | `true` | `boolean` | - | | `trackSessions` | `true` | `boolean` | - | | `trackWebVitals` | `false` | `boolean` | - | | `trackErrors` | `false` | `boolean` | - | | `trackOutgoingLinks` | `false` | `boolean` | - | | `trackScrollDepth` | `false` | `boolean` | - | | `trackEngagement` | `false` | `boolean` | - | | `enableBatching` | `false` | `boolean` | - | | `batchSize` | `10` | `number` | 1-50 | | `batchTimeout` | `2000` | `number` | 100-30000ms | | `samplingRate` | `1.0` | `number` | 0.0-1.0 | | `enableRetries` | `true` | `boolean` | - | | `maxRetries` | `3` | `number` | 0-10 | | `initialRetryDelay` | `500` | `number` | 50-10000ms | | `apiUrl` | `https://basket.databuddy.cc` | `string` | Valid URL | | `scriptUrl` | `https://app.databuddy.cc/databuddy.js` | `string` | Valid URL | ### Environment Variables For React/Next.js projects, set up environment variables: ```bash title=".env.local" # Required NEXT_PUBLIC_DATABUDDY_CLIENT_ID=your-client-id-here # Optional - only for self-hosted instances NEXT_PUBLIC_DATABUDDY_API_URL=https://your-api.example.com ``` **Security**: Never include `clientSecret` in client-side code. It's only for server-side usage. ## 🔍 Debugging & Testing ### Development Mode ```tsx title="Disable tracking in development" ``` ### Browser Console Testing Test custom events in your browser console: ```javascript // Test if SDK is loaded console.log(window.databuddy ? 'SDK loaded ✅' : 'SDK not loaded ❌'); // Send test event db.track('test_event', { source: 'console', timestamp: Date.now() }); // Check network requests // Look for requests to basket.databuddy.cc in Network tab ``` ### Common Issues 1. **Check Client ID**: Verify it matches your dashboard 2. **Check Network Tab**: Look for requests to `basket.databuddy.cc` 3. **Verify Domain**: Ensure your domain is verified in the dashboard 4. **Check Disabled State**: Make sure `disabled` is not `true` 5. **Test Manually**: Try `db.track('test', {})` in console 1. **Install SDK**: Make sure `@databuddy/sdk` is installed 2. **TypeScript Version**: Requires TypeScript 4.5+ 3. **Global Types**: Add global declarations if needed: ```tsx declare global { interface Window { databuddy?: { track: (event: string, properties?: Record) => void; }; } } ``` 1. **Check URL**: Verify `https://app.databuddy.cc/databuddy.js` 2. **Content Security Policy**: Add CSP rules if needed: ``` script-src 'self' https://app.databuddy.cc; connect-src 'self' https://basket.databuddy.cc; ``` 3. **Ad Blockers**: Some ad blockers may block analytics scripts ## 🔗 Related Documentation Quick setup guide and basic configuration Custom events, performance monitoring, and advanced features Navigate your analytics dashboard and understand metrics Privacy settings, GDPR compliance, and data handling file: ./content/docs/security.mdx meta: { "title": "Security & Privacy", "description": "How Databuddy protects your data and respects user privacy" } # Security & Privacy Databuddy is built with privacy-first principles and enterprise-grade security. This guide covers what we do to protect your data and how to configure privacy settings for your users. ## 🔒 Privacy-First Design ### What We Don't Collect * **No Personal Information** - Names, emails, phone numbers, addresses * **No Cookies for Tracking** - Only local storage for anonymous IDs * **No Cross-Site Tracking** - Each site is isolated * **No Fingerprinting** - Respects browser privacy settings * **No Raw IP Addresses** - Only used for location (country/region) then discarded ### What We Do Collect * **Anonymous Usage Data** - Page views, clicks, performance metrics * **Session Information** - Anonymous session IDs with 30-minute timeouts * **Technical Data** - Browser type, screen size, performance metrics * **Location Data** - Country and region only (from IP, then IP discarded) ## 🛡️ Data Protection ### Anonymous by Default ```javascript // All users get anonymous IDs - no personal data { anonymousId: "anon_abc123...", // Random UUID sessionId: "sess_xyz789...", // Session identifier event: "page_view", // What happened path: "/dashboard", // Where it happened // No names, emails, or personal data } ``` ### Local Data Storage * **Anonymous ID** - Stored in localStorage, never sent to servers * **Session Data** - Temporary sessionStorage, clears on browser close * **No Cookies** - We don't use tracking cookies * **User Control** - Easy to clear all data ## 🌍 Privacy Compliance ### GDPR Compliance by Design **Lawful Basis:** Legitimate interest for website analytics Databuddy is **compliant by default** - no consent banners or cookie notices required because: * **No Personal Data Collected** - Only anonymous usage statistics * **No Cookies Used** - Uses localStorage for anonymous IDs only * **No User Identification** - Cannot identify individual users * **Automatic Data Anonymization** - All data is anonymous from collection ### No Consent Required ```tsx import { Databuddy } from '@databuddy/sdk'; function App() { return ( <> {/* No consent needed - privacy-first by design */} {/* No cookie banner needed! */} ); } ``` **Why No Consent Needed:** * Anonymous data only * No cross-site tracking * No personal information * No behavioral profiling * Legitimate interest applies ## ⚙️ Privacy Controls ### Minimal Tracking Setup ```tsx // Essential analytics only ``` ### Development vs Production ```tsx const isProd = process.env.NODE_ENV === 'production'; ``` ## 🔐 Security Features ### Domain Protection * **Domain Verification Required** - Only verified domains can send data * **Origin Validation** - Requests validated against registered domains * **HTTPS Required** - All communications encrypted in transit ### Data Validation * **Input Sanitization** - All user data cleaned and validated * **Size Limits** - Prevents large payloads and spam * **Rate Limiting** - Protects against abuse ### Infrastructure Security * **Enterprise-Grade Hosting** - SOC 2 compliant infrastructure * **DDoS Protection** - Automatic attack mitigation * **Regular Security Audits** - Professional penetration testing * **Encrypted Storage** - All data encrypted at rest ## 🛠️ User Privacy Controls (Optional) ### Anonymous Data Only Since Databuddy only collects anonymous data, users don't need to request data deletion - there's no personal data to delete! However, you can still provide opt-out controls if desired. ### Optional Opt-Out Implementation ```tsx function PrivacyControls() { const [trackingEnabled, setTrackingEnabled] = useState(true); const handleOptOut = () => { // Clear local anonymous ID localStorage.removeItem('databuddy_anon_id'); // Disable tracking setTrackingEnabled(false); // Store preference localStorage.setItem('databuddy_opt_out', 'true'); }; return (

Analytics helps us improve our website. No personal data is collected.

); } ``` ### Why Data Deletion Isn't Needed * **No Personal Data** - Nothing to identify individual users * **Anonymous by Design** - All data is aggregated and anonymous * **No User Profiles** - Cannot build profiles of individual users * **Automatic Expiry** - Data expires automatically over time ## 🌐 Global Privacy Settings ### Respect Browser Preferences ```javascript // Check Do Not Track setting const respectDNT = navigator.doNotTrack === '1'; ``` ## 📋 Privacy Best Practices ### 1. Be Transparent ```tsx // Clear privacy notice function PrivacyNotice() { return (

We respect your privacy

We collect anonymous usage data to improve our website. No personal information is collected. You can opt out anytime.

Read our privacy policy
); } ``` ### 2. Provide Controls (Optional) ```tsx // Optional privacy dashboard (not required since data is anonymous) function PrivacyDashboard() { return (

Analytics Preferences

Anonymous Data Collection

Help us improve our website with anonymous usage statistics.

Your Privacy

✅ No personal data is collected

✅ No cookies are used for tracking

✅ Cannot identify individual users

); } ``` ### 3. Honor Preferences ```tsx // Respect user choices const privacySettings = getUserPrivacySettings(); ``` ## ⚖️ Legal Compliance ### Recommended Disclosures **Privacy Policy Should Include:** * Anonymous analytics are collected via Databuddy * No personal information or cookies are used * Data is used only for website improvement * Optional: How users can opt-out **Cookie Notice:** * **Not required for Databuddy** (no cookies used) * Only needed if you use other tracking tools ### Sample Privacy Policy Text ``` Analytics: We use Databuddy to collect anonymous website usage statistics to help us improve our site. No personal information, cookies, or tracking is used. All data is completely anonymous and cannot identify individual visitors. Data is processed securely by Databuddy and used only for understanding website performance and usage patterns. ``` ### Minimal Privacy Notice ``` We collect anonymous usage statistics to improve our website. No personal data or cookies are used. ``` ## 🛡️ Implementation Security ### Content Security Policy ```html ``` ### Secure Configuration ```tsx // Environment-specific settings const config = { development: { clientId: process.env.NEXT_PUBLIC_DATABUDDY_DEV_ID, disabled: true, // No tracking in development }, production: { clientId: process.env.NEXT_PUBLIC_DATABUDDY_PROD_ID, disabled: false, } }[process.env.NODE_ENV]; ``` ## 🆘 Support & Questions ### Privacy Questions If you have questions about privacy or data handling: * 📧 [privacy@databuddy.cc](mailto:privacy@databuddy.cc) * 📚 [Privacy Policy](https://databuddy.cc/privacy) * 🛡️ [Security Overview](https://databuddy.cc/docs/security) ### Data Requests **No data requests needed** - Databuddy doesn't collect personal data that can identify users. If you have questions about our data handling: * 📧 [privacy@databuddy.cc](mailto:privacy@databuddy.cc) *** ## What's Next? * **[SDK Reference](/docs/sdk)** - Configure tracking options * **[Getting Started](/docs/getting-started)** - Set up Databuddy on your site * **[Dashboard Guide](/docs/dashboard)** - Analyze your anonymous data file: ./content/docs/Integrations/framer.mdx meta: { "title": "Framer", "description": "Add privacy-first analytics to your Framer site" } # Framer Integration Databuddy enables you to gather privacy-first analytics on user behavior, capture custom events, track performance metrics, and more within your Framer site - all while maintaining GDPR compliance without cookies. ## How to Add Databuddy to Framer ### 1. Get Your Tracking Script Navigate to your [Databuddy dashboard](https://app.databuddy.cc) and copy your tracking code snippet: ```html ``` ### 2. Add the Script to Your Framer Project 1. Open your Framer project 2. Go to **Site Settings** > **General** 3. Scroll down to **Custom Code** 4. Paste your Databuddy snippet into the **Start of \ tag** section 5. Click **Save** and publish your changes ### 3. Verify Installation Once published, you can verify that Databuddy is working by: 1. Visiting your live Framer site 2. Opening your browser's developer tools (F12) 3. Checking the Console tab for a "Databuddy initialized" message 4. Visiting your Databuddy dashboard to see real-time analytics ## Advanced Features ### Custom Event Tracking Track custom interactions in your Framer components using data attributes: ```html
``` ### Performance Monitoring Enable performance tracking by updating your script configuration: ```html ``` ## Benefits for Framer Sites * **Lightweight**: Only 3KB script size (247x smaller than Google Analytics) * **Fast Loading**: Async loading won't slow down your Framer site * **SEO Friendly**: Improves Core Web Vitals and page speed scores * **Privacy Compliant**: No cookies required, fully GDPR/CCPA compliant * **Real-time Data**: See visitor activity as it happens ## Troubleshooting ### Script Not Loading If Databuddy isn't working: 1. Ensure the script is in the **Start of \ tag** section 2. Check that your Site ID is correct 3. Verify your site is published (not just preview mode) 4. Check browser console for any error messages ### Data Not Appearing If analytics data isn't showing: 1. Wait 2-3 minutes for data processing 2. Check that your domain is verified in Databuddy dashboard 3. Ensure you're viewing the correct date range 4. Try visiting your site in an incognito window Need help? Contact our support team at [help@databuddy.cc](mailto:help@databuddy.cc). file: ./content/docs/Integrations/gtm.mdx meta: { "title": "Google Tag Manager", "description": "Add Databuddy analytics through Google Tag Manager" } # Google Tag Manager Integration Integrate Databuddy with Google Tag Manager for centralized tag management while maintaining privacy-first analytics. Perfect for teams managing multiple tracking tools. ## Why Use GTM with Databuddy? * **Centralized Management**: Manage Databuddy alongside other marketing tools * **Team Collaboration**: Non-developers can deploy tracking updates * **Version Control**: Built-in versioning and rollback capabilities * **Testing**: Preview and debug mode before publishing * **Conditional Loading**: Load Databuddy based on specific conditions ## Basic Setup ### Step 1: Create Databuddy Tag 1. In GTM, click **Add a new tag** 2. Choose **Custom HTML** as the tag type 3. Add the Databuddy script: > **Important**: GTM sanitizes HTML and removes non-standard attributes like `data-client-id`. Always use `createElement()` and `setAttribute()` as shown below: ```html ``` 4. Name your tag "Databuddy - Analytics Script" ### Step 2: Create Variables Create a **Constant** variable for your Site ID: 1. Go to **Variables** > **User-Defined Variables** 2. Click **New** > **Constant** 3. Name: "Databuddy Site ID" 4. Value: Your actual Site ID from Databuddy dashboard ### Step 3: Set Trigger 1. In your Databuddy tag, click **Triggering** 2. Choose **All Pages** trigger 3. Save the tag ### Step 4: Publish 1. Click **Submit** to create a version 2. Add version name and description 3. Click **Publish** ## Advanced Configuration ### Environment-Based Loading Load different Databuddy configurations based on environment: ```html ``` ### Conditional Loading Load Databuddy only for specific conditions: ```html ``` ## Event Tracking Setup ### Custom Event Tags Create tags for specific events: **E-commerce Purchase Tag:** ```html ``` **Form Submission Tag:** ```html ``` ### Data Layer Integration Send GTM data layer events to Databuddy: ```html ``` ## Triggers Configuration ### Page View Tracking Create a trigger for enhanced page views: 1. **Trigger Type**: Page View - DOM Ready 2. **Trigger Name**: "Databuddy - Enhanced Page View" 3. **Conditions**: Page Path contains your domain ### Scroll Tracking Set up scroll depth tracking: 1. **Trigger Type**: Scroll Depth 2. **Vertical Scroll Depths**: 25, 50, 75, 90 3. **Tag**: Custom HTML with scroll tracking ```html ``` ### Click Tracking Track specific button clicks: 1. **Trigger Type**: Click - All Elements 2. **Conditions**: Click Classes contains "track-button" 3. **Tag**: Custom HTML with click tracking ```html ``` ## E-commerce Integration ### Enhanced E-commerce Setup Track the complete customer journey: **Product View Tag:** ```html ``` **Add to Cart Tag:** ```html ``` **Begin Checkout Tag:** ```html ``` ## User Privacy and Consent ### GDPR Compliance Respect user privacy choices: ```html ``` ### Consent Mode Integration Integrate with Google Consent Mode: ```html ``` ## Debugging and Testing ### Debug Mode Setup Enable debug mode for testing: ```html ``` ### Preview Mode Testing 1. Click **Preview** in GTM 2. Visit your website in the debug session 3. Verify Databuddy tags are firing correctly 4. Check browser console for any errors 5. Confirm events in Databuddy dashboard ### Variable Testing Create test variables for debugging: **Debug Info Variable:** ```javascript function() { return { page_path: {{Page Path}}, page_title: {{Page Title}}, user_agent: navigator.userAgent, timestamp: new Date().toISOString() }; } ``` ## Best Practices ### Performance Optimization 1. **Async Loading**: Always load Databuddy asynchronously 2. **Conditional Loading**: Only load when necessary 3. **Error Handling**: Wrap in try-catch blocks ```html ``` ### Tag Organization 1. **Naming Convention**: Use clear, descriptive names 2. **Folders**: Organize tags by vendor or purpose 3. **Notes**: Add descriptions explaining each tag's purpose 4. **Triggers**: Name triggers clearly (e.g., "Databuddy - All Pages") ### Version Management 1. **Descriptive Names**: Use meaningful version names 2. **Notes**: Document changes in each version 3. **Testing**: Always test in preview before publishing 4. **Rollback Plan**: Know how to revert if issues arise ## Migration from Google Analytics ### Replacing GA4 with Databuddy 1. **Pause GA4 tags** (don't delete immediately) 2. **Create Databuddy tags** with equivalent functionality 3. **Test thoroughly** in preview mode 4. **Gradual rollout** using percentage-based triggers 5. **Monitor data** for consistency ### Data Mapping Map GA4 events to Databuddy equivalents: | GA4 Event | Databuddy Event | Notes | | ------------- | --------------- | ------------------------------- | | page\_view | screen\_view | Automatic with trackScreenViews | | purchase | purchase | Enhanced with privacy features | | add\_to\_cart | add\_to\_cart | Same structure | | scroll | scroll\_depth | Custom implementation | ## Troubleshooting ### Common Issues **Tag Not Firing:** * Check trigger conditions * Verify variable values in preview mode * Ensure GTM code is properly installed **Events Not Tracking:** * Verify Databuddy script loads successfully * Check browser console for errors * Confirm Site ID is correct **Performance Issues:** * Ensure scripts load asynchronously * Check for blocking JavaScript errors * Monitor Core Web Vitals impact ### Debug Checklist 1. ✅ GTM container code installed correctly 2. ✅ Databuddy tag fires on correct triggers 3. ✅ Site ID variable contains correct value 4. ✅ No JavaScript errors in console 5. ✅ Events appear in Databuddy dashboard 6. ✅ Privacy settings respected Need help with your GTM integration? Contact us at [help@databuddy.cc](mailto:help@databuddy.cc). file: ./content/docs/Integrations/nextjs.mdx meta: { "title": "Next.js", "description": "Add privacy-first analytics to your Next.js application" } # Next.js Integration Integrate Databuddy with your Next.js application for server-side rendering support, automatic page tracking, and optimal performance. ## Installation Install the Databuddy SDK: ```bash npm install @databuddy/sdk ``` or with yarn: ```bash yarn add @databuddy/sdk ``` ## App Router Setup (Next.js 13+) ### 1. Add Script Component to Layout ```tsx // app/layout.tsx import { Databuddy } from '@databuddy/sdk'; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( {children} ); } ``` ### 2. Track Route Changes (Optional) If you need custom route tracking: ```tsx // app/analytics.tsx 'use client'; import { useEffect } from 'react'; import { usePathname, useSearchParams } from 'next/navigation'; import { track } from '@databuddy/sdk'; export function Analytics() { const pathname = usePathname(); const searchParams = useSearchParams(); useEffect(() => { const url = pathname + searchParams.toString(); track('screen_view', { screen_name: pathname, screen_class: 'Next.js', url: url }); }, [pathname, searchParams]); return null; } ``` Then add to your root layout: ```tsx // app/layout.tsx import { Databuddy } from '@databuddy/sdk'; import { Analytics } from './analytics'; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( {children} ); } ``` ## Pages Router Setup (Next.js 12 and below) ### 1. Add to \_app.tsx ```tsx // pages/_app.tsx import type { AppProps } from 'next/app'; import { Databuddy } from '@databuddy/sdk'; import { useRouter } from 'next/router'; import { useEffect } from 'react'; import { track } from '@databuddy/sdk'; function MyApp({ Component, pageProps }: AppProps) { const router = useRouter(); useEffect(() => { const handleRouteChange = (url: string) => { track('screen_view', { screen_name: url, screen_class: 'Next.js' }); }; router.events.on('routeChangeComplete', handleRouteChange); return () => { router.events.off('routeChangeComplete', handleRouteChange); }; }, [router.events]); return ( <> ); } export default MyApp; ``` ### Alternative: Manual Script in \_document.tsx If you prefer to add the script manually: ```tsx // pages/_document.tsx import { Html, Head, Main, NextScript } from 'next/document'; export default function Document() { return ( ``` ### Method 2: Google Tag Manager If you're using Google Tag Manager: 1. In GTM, create a new **Custom HTML** tag 2. Add the Databuddy script: ```html ``` 3. Set trigger to **All Pages** 4. Publish the container ## E-commerce Tracking ### Track Product Views Add to your `product.liquid` template: ```html ``` ### Track Add to Cart Add to your product form or use data attributes: ```html ``` ### Track Purchases Add to your `thank-you.liquid` or checkout success page: ```html {% if first_time_accessed %} {% endif %} ``` ## Customer Behavior Tracking ### Track Search Events Add to your `search.liquid` template: ```html {% if search.performed %} {% endif %} ``` ### Track Collection Views Add to your `collection.liquid` template: ```html ``` ### Track Newsletter Signups For newsletter forms: ```html ``` ## Advanced Configuration ### Customer Identification Track logged-in customers: ```html {% if customer %} {% endif %} ``` ### Cart Abandonment Tracking Track when users add items but don't complete purchase: ```html ``` ## Shopify Plus Features ### Checkout Extensions For Shopify Plus stores using checkout extensions: ```javascript // In your checkout extension import { extension, Banner } from '@shopify/ui-extensions/checkout'; extension('purchase.checkout.block.render', (root, api) => { const { analytics } = api; // Track checkout steps analytics.track('checkout_step', { step: 'information', checkout_id: api.checkoutToken }); }); ``` ### Flow Integration Use Shopify Flow to trigger Databuddy events: 1. Create a new Flow in Shopify admin 2. Set trigger (e.g., "Order created") 3. Add HTTP request action: * URL: `https://api.databuddy.cc/events` * Method: POST * Headers: `Authorization: Bearer YOUR_API_KEY` * Body: Order data in JSON format ## Performance Optimization ### Lazy Loading Load Databuddy after critical resources: ```html ``` ### Mobile Optimization Optimize for mobile users: ```html ``` ## Compliance and Privacy ### GDPR Compliance Databuddy is GDPR compliant by default, but you can add additional privacy controls: ```html {% if localization.country.iso_code == 'EU' %} {% endif %} ``` ### Cookie Consent Integration If using a cookie consent banner: ```javascript // Wait for consent before tracking function initializeDatabuddy() { var script = document.createElement('script'); script.src = 'https://app.databuddy.cc/databuddy.js'; script.setAttribute('data-client-id', 'YOUR_SITE_ID'); script.async = true; document.head.appendChild(script); } // Call after user accepts cookies document.addEventListener('cookieConsentAccepted', initializeDatabuddy); ``` ## Troubleshooting ### Common Issues **Script Not Loading**: Check if your theme has Content Security Policy restrictions. **Events Not Tracking**: Verify that your Site ID is correct and the script is loading without errors. **Liquid Syntax Errors**: Ensure all Liquid variables are properly escaped and quoted. ### Testing Test your implementation: 1. Use Shopify's preview theme feature 2. Check browser console for any JavaScript errors 3. Verify events in your Databuddy dashboard 4. Test on mobile devices ### Debug Mode Enable debug mode for development: ```html ``` Need help with your Shopify integration? Contact us at [help@databuddy.cc](mailto:help@databuddy.cc). file: ./content/docs/Integrations/stripe.mdx meta: { "title": "Stripe", "description": "Track revenue analytics with Stripe webhook integration" } # Stripe Integration Connect Stripe payments to Databuddy's analytics to track revenue, conversion funnels, and customer behavior. This integration automatically links payment events to your website analytics for complete revenue attribution. ## Overview The Stripe integration captures: * **Payment Intents**: Track payment attempts, successes, and failures * **Charges**: Monitor successful payments and refunds * **Refunds**: Track refund events and amounts * **Revenue Attribution**: Link payments to specific user sessions and marketing campaigns All payment data is automatically linked to your website analytics using session IDs, enabling powerful revenue attribution and conversion tracking. ## Prerequisites Before setting up the Stripe integration, ensure you have: 1. **Databuddy Account**: [Sign up](https://app.databuddy.cc) and get your Client ID 2. **Stripe Account**: Active Stripe account with API access 3. **Website Analytics**: Databuddy tracking script installed on your website 4. **Server-side Integration**: Ability to modify your server-side Stripe checkout code ## How Session Tracking Works Databuddy automatically handles session and user IDs: ### Automatic Session Management * **Session ID**: Automatically generated and stored in `sessionStorage` as `did_session` * **Session Format**: `sess_{timestamp}_{random_string}` (e.g., `sess_lm8k9x_abc123def456`) * **Session Duration**: 30 minutes of inactivity, then a new session is created ### Anonymous User Tracking * **Anonymous ID**: Automatically generated and stored in `localStorage` as `did` * **Anonymous Format**: `anon_{uuid}` (e.g., `anon_123e4567-e89b-12d3-a456-426614174000`) * **Persistence**: Persists across browser sessions until localStorage is cleared * **Privacy**: No personal information is stored, fully anonymous ### Data Linking When you pass the session ID to Stripe via `client_reference_id`, Databuddy can: * Link payment events to specific user sessions * Track the complete customer journey from first visit to purchase * Attribute revenue to marketing campaigns and traffic sources * Calculate conversion rates and customer lifetime value ## Setup Process ### Step 1: Ensure Databuddy Script is Properly Configured Before setting up webhooks, make sure your Databuddy tracking script is configured correctly: ```html ``` **Important Configuration Options**: * `data-track-sessions="true"` - **Required** for session tracking (default: true) * `data-client-id` - **Required** - Your Databuddy Client ID ### Step 2: Configure Webhook Endpoint 1. **Log into your Databuddy Dashboard** 2. **Navigate to Integrations** > **Stripe** 3. **Create a new Stripe configuration**: * Enter your **Stripe Webhook Secret** (we'll get this in Step 2) * Choose **Test Mode** or **Live Mode** * Copy your unique **Webhook URL** (e.g., `https://basket.databuddy.cc/stripe/webhook/wh_abc123`) ### Step 3: Create Stripe Webhook 1. **Log into your Stripe Dashboard** 2. **Go to Developers** > **Webhooks** 3. **Click "Add endpoint"** 4. **Configure the webhook**: * **Endpoint URL**: Paste your Databuddy webhook URL from Step 1 * **Events to send**: Select these specific events: ``` payment_intent.succeeded payment_intent.created payment_intent.canceled payment_intent.payment_failed payment_intent.requires_action charge.succeeded charge.failed charge.captured charge.dispute.created refund.created refund.updated refund.failed ``` 5. **Click "Add endpoint"** 6. **Copy the Webhook Secret**: * Click on your newly created webhook * In the "Signing secret" section, click "Reveal" * Copy the secret (starts with `whsec_`) 7. **Return to Databuddy** and paste the webhook secret ### Step 4: Update Your Checkout Code Modify your server-side Stripe checkout session creation to include required metadata: > **Important**: You must set metadata on both the checkout session AND the payment intent. Metadata set only on the checkout session does not automatically propagate to payment intents and charges, which is what the webhook processes. #### Node.js/JavaScript Example ```javascript const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY); // Create checkout session const session = await stripe.checkout.sessions.create({ payment_method_types: ['card'], mode: 'payment', line_items: [ { price: 'price_1234567890', // Your price ID quantity: 1, }, ], success_url: 'https://yoursite.com/success?session_id={CHECKOUT_SESSION_ID}', cancel_url: 'https://yoursite.com/cancel', // REQUIRED: Link to your analytics client_reference_id: sessionId, // Your analytics session ID metadata: { client_id: 'your_databuddy_client_id', // Your Databuddy Client ID // Optional: Add any custom metadata user_id: 'user_123', campaign: 'summer_sale', }, // CRITICAL: Set metadata on payment intent so it propagates to charges payment_intent_data: { metadata: { client_id: 'your_databuddy_client_id', // Required for webhook processing session_id: sessionId, // Required for analytics tracking // Optional: Add any custom metadata user_id: 'user_123', campaign: 'summer_sale', }, }, }); ``` #### Python Example ```python import stripe stripe.api_key = os.environ['STRIPE_SECRET_KEY'] session = stripe.checkout.Session.create( payment_method_types=['card'], mode='payment', line_items=[{ 'price': 'price_1234567890', # Your price ID 'quantity': 1, }], success_url='https://yoursite.com/success?session_id={CHECKOUT_SESSION_ID}', cancel_url='https://yoursite.com/cancel', # REQUIRED: Link to your analytics client_reference_id=session_id, # Your analytics session ID metadata={ 'client_id': 'your_databuddy_client_id', # Your Databuddy Client ID # Optional: Add any custom metadata 'user_id': 'user_123', 'campaign': 'summer_sale', }, # CRITICAL: Set metadata on payment intent so it propagates to charges payment_intent_data={ 'metadata': { 'client_id': 'your_databuddy_client_id', # Required for webhook processing 'session_id': session_id, # Required for analytics tracking # Optional: Add any custom metadata 'user_id': 'user_123', 'campaign': 'summer_sale', }, }, ) ``` #### PHP Example ```php ['card'], 'mode' => 'payment', 'line_items' => [[ 'price' => 'price_1234567890', // Your price ID 'quantity' => 1, ]], 'success_url' => 'https://yoursite.com/success?session_id={CHECKOUT_SESSION_ID}', 'cancel_url' => 'https://yoursite.com/cancel', // REQUIRED: Link to your analytics 'client_reference_id' => $sessionId, // Your analytics session ID 'metadata' => [ 'client_id' => 'your_databuddy_client_id', // Your Databuddy Client ID // Optional: Add any custom metadata 'user_id' => 'user_123', 'campaign' => 'summer_sale', ], // CRITICAL: Set metadata on payment intent so it propagates to charges 'payment_intent_data' => [ 'metadata' => [ 'client_id' => 'your_databuddy_client_id', // Required for webhook processing 'session_id' => $sessionId, // Required for analytics tracking // Optional: Add any custom metadata 'user_id' => 'user_123', 'campaign' => 'summer_sale', ], ], ]); ?> ``` ### Step 5: Get Your Analytics Session ID The `client_reference_id` should contain your website's analytics session ID. Databuddy automatically generates and manages session IDs, so you can easily access them: #### Frontend JavaScript ```javascript // Get the session ID from Databuddy let sessionId; // Method 1: From Databuddy sessionStorage (automatic generation) // Databuddy stores session ID in sessionStorage as 'did_session' if (typeof window !== 'undefined' && sessionStorage) { sessionId = sessionStorage.getItem('did_session'); } // Method 2: If Databuddy hasn't initialized yet, wait for it if (!sessionId && window.databuddy) { // Access the session ID directly from the Databuddy instance sessionId = window.databuddy.sessionId; } // Method 3: Wait for Databuddy to initialize if (!sessionId) { // Databuddy will automatically generate a session ID when it loads // You can wait for it or check periodically const waitForDatabuddy = () => { if (window.databuddy && window.databuddy.sessionId) { sessionId = window.databuddy.sessionId; createCheckoutSession(sessionId); } else { setTimeout(waitForDatabuddy, 100); } }; waitForDatabuddy(); return; // Exit early, will continue in callback } // Send to your backend when creating checkout createCheckoutSession(sessionId); function createCheckoutSession(sessionId) { fetch('/create-checkout-session', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ sessionId: sessionId, // ... other checkout data }), }); } ``` #### Alternative: Use a Helper Function ```javascript // Helper function to get session ID reliably function getDatabuddySessionId() { return new Promise((resolve) => { // Check if session ID is already available const existingSessionId = sessionStorage.getItem('did_session'); if (existingSessionId) { resolve(existingSessionId); return; } // Wait for Databuddy to initialize and generate session ID const checkForSession = () => { const sessionId = sessionStorage.getItem('did_session') || (window.databuddy && window.databuddy.sessionId); if (sessionId) { resolve(sessionId); } else { setTimeout(checkForSession, 50); } }; checkForSession(); }); } // Usage async function handleCheckout() { const sessionId = await getDatabuddySessionId(); const response = await fetch('/create-checkout-session', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId: sessionId, clientId: 'your_databuddy_client_id', // ... other data }), }); const { url } = await response.json(); window.location.href = url; } ``` ## Implementation Examples ### React/Next.js Integration ```jsx import { useState, useEffect } from 'react'; function CheckoutButton({ priceId, productName }) { const [sessionId, setSessionId] = useState(null); const [isLoading, setIsLoading] = useState(false); useEffect(() => { // Get session ID from Databuddy (automatically generated) const getSessionId = () => { // Check if session ID is already available in sessionStorage const existingSessionId = sessionStorage.getItem('did_session'); if (existingSessionId) { setSessionId(existingSessionId); return; } // Wait for Databuddy to initialize and generate session ID const checkForSession = () => { const sessionId = sessionStorage.getItem('did_session') || (window.databuddy && window.databuddy.sessionId); if (sessionId) { setSessionId(sessionId); } else { setTimeout(checkForSession, 100); } }; checkForSession(); }; getSessionId(); }, []); const handleCheckout = async () => { if (!sessionId) { console.warn('Session ID not available yet'); return; } setIsLoading(true); try { const response = await fetch('/api/create-checkout-session', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ priceId, sessionId, clientId: process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID, }), }); const { url } = await response.json(); window.location.href = url; } catch (error) { console.error('Checkout error:', error); setIsLoading(false); } }; return ( ); } ``` #### Custom Hook for Session Management ```jsx import { useState, useEffect } from 'react'; // Custom hook to manage Databuddy session ID function useDatabuddySession() { const [sessionId, setSessionId] = useState(null); const [isReady, setIsReady] = useState(false); useEffect(() => { const getSessionId = async () => { return new Promise((resolve) => { // Check if session ID is already available const existingSessionId = sessionStorage.getItem('did_session'); if (existingSessionId) { resolve(existingSessionId); return; } // Wait for Databuddy to initialize const checkForSession = () => { const sessionId = sessionStorage.getItem('did_session') || (window.databuddy && window.databuddy.sessionId); if (sessionId) { resolve(sessionId); } else { setTimeout(checkForSession, 50); } }; checkForSession(); }); }; getSessionId().then((id) => { setSessionId(id); setIsReady(true); }); }, []); return { sessionId, isReady }; } // Usage in component function CheckoutButton({ priceId, productName }) { const { sessionId, isReady } = useDatabuddySession(); const [isLoading, setIsLoading] = useState(false); const handleCheckout = async () => { if (!sessionId) return; setIsLoading(true); // ... checkout logic }; return ( ); } ``` ### API Route (Next.js) ```javascript // pages/api/create-checkout-session.js or app/api/stripe/checkout/route.ts import Stripe from 'stripe'; const stripe = new Stripe(process.env.STRIPE_SECRET_KEY); export default async function handler(req, res) { if (req.method !== 'POST') { return res.status(405).json({ error: 'Method not allowed' }); } const { priceId, sessionId, clientId } = req.body; try { const session = await stripe.checkout.sessions.create({ payment_method_types: ['card'], mode: 'payment', line_items: [ { price: priceId, quantity: 1, }, ], success_url: `${req.headers.origin}/success?session_id={CHECKOUT_SESSION_ID}`, cancel_url: `${req.headers.origin}/cancel`, // REQUIRED: Link to analytics client_reference_id: sessionId, metadata: { client_id: clientId, }, // CRITICAL: Set metadata on payment intent so it propagates to charges payment_intent_data: { metadata: { client_id: clientId, // Required for webhook processing session_id: sessionId, // Required for analytics tracking }, }, }); res.json({ url: session.url }); } catch (error) { console.error('Error creating checkout session:', error); res.status(500).json({ error: 'Failed to create checkout session' }); } } ``` ### Express.js Integration ```javascript const express = require('express'); const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY); app.post('/create-checkout-session', async (req, res) => { const { priceId, sessionId, clientId } = req.body; try { const session = await stripe.checkout.sessions.create({ payment_method_types: ['card'], mode: 'payment', line_items: [ { price: priceId, quantity: 1, }, ], success_url: 'https://yoursite.com/success?session_id={CHECKOUT_SESSION_ID}', cancel_url: 'https://yoursite.com/cancel', // REQUIRED: Link to analytics client_reference_id: sessionId, metadata: { client_id: clientId, }, // CRITICAL: Set metadata on payment intent so it propagates to charges payment_intent_data: { metadata: { client_id: clientId, // Required for webhook processing session_id: sessionId, // Required for analytics tracking }, }, }); res.json({ url: session.url }); } catch (error) { console.error('Error:', error); res.status(500).json({ error: 'Failed to create session' }); } }); ``` ## Testing Your Integration ### 1. Test Mode Setup 1. **Use Stripe Test Mode**: Ensure your webhook is configured for test mode 2. **Use Test Cards**: Use Stripe's test card numbers 3. **Monitor Webhook Events**: Check your Databuddy dashboard for incoming events ### 2. Test Card Numbers Use these Stripe test cards: * **Successful Payment**: `4242424242424242` * **Payment Requires Authentication**: `4000002500003155` * **Payment Fails**: `4000000000000002` * **Insufficient Funds**: `4000000000009995` ### 3. Verify Data Flow 1. **Create a test purchase** using a test card 2. **Check Stripe Dashboard**: Verify the webhook was called successfully 3. **Check Databuddy Dashboard**: Confirm payment data appears in your analytics 4. **Verify Attribution**: Ensure payment is linked to the correct session ## Important: Metadata Propagation ### Why payment\_intent\_data is Required Stripe's checkout sessions, payment intents, and charges are **separate objects** with independent metadata. When you set metadata on a checkout session, it does **NOT** automatically copy to the associated payment intent or charges. Since Databuddy's webhook processes individual payment events (charges, payment intents), the metadata must be present on those specific objects. This is why you must use `payment_intent_data.metadata` in addition to the session metadata. **What happens without payment\_intent\_data**: * ✅ Checkout session has metadata * ❌ Payment intent has empty metadata: `{}` * ❌ Charge has empty metadata: `{}` * ❌ Webhook fails: "Missing required client\_id" **What happens with payment\_intent\_data**: * ✅ Checkout session has metadata * ✅ Payment intent has metadata with client\_id * ✅ Charge inherits metadata from payment intent * ✅ Webhook processes successfully ## Troubleshooting ### Common Issues #### Webhook Not Receiving Events **Problem**: Stripe webhook shows failed deliveries **Solutions**: * Verify your webhook URL is correct and accessible * Check that your webhook secret matches exactly * Ensure your server accepts POST requests * Verify SSL certificate is valid #### Missing client\_id Error **Problem**: Webhook receives events but shows "Missing required client\_id" error **Solutions**: * Ensure `metadata.client_id` is set in your checkout session * **CRITICAL**: Add `payment_intent_data.metadata` with the same client\_id - metadata on checkout sessions does NOT automatically propagate to payment intents and charges * Verify the client\_id matches your Databuddy Client ID exactly * Check that metadata is being passed correctly **Example of the fix**: ```javascript const session = await stripe.checkout.sessions.create({ // ... other config metadata: { client_id: 'your_client_id', // This stays on the session }, payment_intent_data: { metadata: { client_id: 'your_client_id', // This goes to payment intent & charges session_id: sessionId, }, }, }); ``` #### Session ID Not Linking **Problem**: Payments appear in Databuddy but aren't linked to user sessions **Solutions**: * Verify `client_reference_id` contains the correct session ID from `sessionStorage.getItem('did_session')` * Ensure Databuddy has initialized before creating the checkout session * Check that the session ID format matches: `sess_{timestamp}_{random_string}` * Verify the session ID exists in your analytics events by checking the Databuddy dashboard * Make sure the session hasn't expired (30-minute timeout) between page load and checkout #### Session ID Not Available **Problem**: `sessionStorage.getItem('did_session')` returns null **Solutions**: * Ensure Databuddy script is loaded and initialized before accessing session ID * Check that `data-track-sessions` is not set to `false` in your Databuddy script * Verify sessionStorage is available (not in private/incognito mode with restrictions) * Wait for Databuddy initialization using the helper functions provided above * Check browser console for any Databuddy initialization errors #### Webhook Signature Verification Failed **Problem**: Webhook returns "Invalid signature" error **Solutions**: * Verify webhook secret is correct (starts with `whsec_`) * Ensure webhook secret matches between Stripe and Databuddy * Check that webhook endpoint URL is exactly as configured ### Debug Mode Enable debug logging in your Databuddy dashboard: 1. Go to **Integrations** > **Stripe** 2. Enable **Debug Mode** 3. Monitor webhook logs for detailed error information ## Security Considerations ### IP Validation Databuddy automatically validates that webhook requests come from Stripe's official IP addresses. This prevents malicious requests from unauthorized sources. ### Signature Verification All webhook payloads are cryptographically verified using your webhook secret to ensure authenticity and prevent tampering. ### Data Privacy * Payment data is processed securely and stored encrypted * Only necessary payment metadata is stored for analytics * Full PCI compliance maintained through Stripe's infrastructure ## Advanced Configuration ### Custom Metadata Add custom metadata to track additional information: ```javascript const session = await stripe.checkout.sessions.create({ // ... other configuration metadata: { client_id: 'your_databuddy_client_id', // Required user_id: 'user_123', // Optional campaign: 'summer_sale', // Optional source: 'email_campaign', // Optional affiliate_id: 'aff_456', // Optional }, }); ``` ### Multiple Environments Set up separate webhooks for different environments: * **Development**: Use test mode with localhost tunneling (ngrok) * **Staging**: Use test mode with staging webhook URL * **Production**: Use live mode with production webhook URL ### Subscription Tracking For subscription businesses, also track these events: ``` customer.subscription.created customer.subscription.updated customer.subscription.deleted invoice.payment_succeeded invoice.payment_failed ``` ## Analytics and Reporting Once configured, you'll have access to: ### Revenue Analytics * Total revenue by time period * Average order value * Conversion rates * Payment method analysis ### Customer Insights * Customer lifetime value * Purchase frequency * Geographic revenue distribution * Device and browser revenue attribution ### Marketing Attribution * Revenue by traffic source * Campaign performance * UTM parameter tracking * Customer journey analysis ## Support Need help with your Stripe integration? * **Documentation**: Check our [API documentation](/docs/api) * **Support**: Contact [support@databuddy.cc](mailto:support@databuddy.cc) * **Community**: Join our [Discord community](https://discord.gg/JTk7a38tCZ) *** **Next Steps**: Once your Stripe integration is working, explore our [Dashboard](/docs/dashboard) to analyze your revenue data and [API](/docs/api) to build custom reports. file: ./content/docs/Integrations/wordpress.mdx meta: { "title": "WordPress", "description": "Add privacy-first analytics to your WordPress site" } # WordPress Integration Add Databuddy's privacy-first analytics to your WordPress site without slowing it down. No cookies, fully GDPR compliant, and 247x smaller than Google Analytics. ## Installation Methods ### Method 1: WordPress Plugin (Recommended) The easiest way to add Databuddy to WordPress: 1. Download the [Databuddy WordPress Plugin](https://wordpress.org/plugins/databuddy-analytics/) 2. Go to **Plugins** > **Add New** > **Upload Plugin** 3. Upload and activate the plugin 4. Go to **Settings** > **Databuddy Analytics** 5. Enter your Site ID from your [Databuddy dashboard](https://app.databuddy.cc) 6. Configure your tracking preferences 7. Save changes ### Method 2: Manual Header Installation If you prefer manual installation: 1. Get your tracking script from your [Databuddy dashboard](https://app.databuddy.cc) 2. Go to **Appearance** > **Theme Editor** 3. Select **header.php** 4. Add your script before the closing `` tag: ```html ``` ### Method 3: Using a Plugin (Insert Headers and Footers) For a safer approach without editing theme files: 1. Install the "Insert Headers and Footers" plugin 2. Go to **Settings** > **Insert Headers and Footers** 3. Paste your Databuddy script in the "Scripts in Header" section 4. Save settings ## WordPress-Specific Features ### WooCommerce Integration Track e-commerce events automatically: ```html ``` ### Contact Form Tracking Track form submissions from popular WordPress form plugins: ```html ``` ### Custom Post Type Tracking Track views of custom post types: ```php // Add to your theme's functions.php function databuddy_track_custom_post() { if (is_singular('your_custom_post_type')) { echo ''; } } add_action('wp_footer', 'databuddy_track_custom_post'); ``` ## Configuration Options ### Basic Setup ```html ``` ### Advanced Configuration ```html ``` ## WordPress Performance Benefits * **Faster Loading**: Improves your WordPress Core Web Vitals scores * **Lower Bounce Rate**: Better user experience leads to longer session times * **SEO Boost**: Improved performance metrics help search rankings * **Resource Efficient**: Minimal server load compared to other analytics solutions ## Common WordPress Scenarios ### Membership Sites Track member engagement and content consumption: ```html ``` ### Blog Sites Track reading engagement and popular content: ```html
``` ### Business Sites Track lead generation and conversions: ```html Get Quote ``` ## Troubleshooting ### Common Issues **Plugin Conflicts**: If experiencing issues, temporarily deactivate other analytics plugins to identify conflicts. **Caching Issues**: Clear your WordPress cache after installation (WP Rocket, W3 Total Cache, etc.). **Theme Issues**: If manual installation doesn't work, ensure your theme includes `wp_head()` in header.php. ### Verification Steps 1. Check browser console for "Databuddy initialized" message 2. Visit your Databuddy dashboard after 2-3 minutes 3. Use browser dev tools to verify script is loading 4. Test in incognito mode to avoid cache issues ## WordPress Multisite For WordPress multisite networks: 1. Install as a network plugin 2. Configure each site individually with its own Site ID 3. Use network admin settings for global configurations Need help with your WordPress integration? Contact us at [help@databuddy.cc](mailto:help@databuddy.cc). file: ./content/docs/comparisons/best-analytics-tools-2024.mdx meta: { "title": "Best Web Analytics Tools 2025: Complete Comparison Guide", "description": "Compare the top web analytics tools in 2025. Find the best analytics solution for your business with our comprehensive review of features, pricing, and privacy.", "icon": "TrendingUp" } # Best Web Analytics Tools 2025: Complete Comparison Guide Choosing the right web analytics tool is crucial for understanding your website's performance and making data-driven decisions. This comprehensive guide compares the top analytics platforms available in 2025. ## Quick Comparison Table | Tool | Privacy | Pricing | Setup | GDPR | Best For | | ---------------- | ------- | --------- | ------- | ---- | ------------------------ | | **Databuddy** | ⭐⭐⭐⭐⭐ | $9-99/mo | 2 min | ✅ | Privacy-first businesses | | Google Analytics | ⭐⭐ | Free | 30 min | ❌ | Google Ads users | | Adobe Analytics | ⭐⭐⭐ | $$$$ | Complex | ⚠️ | Enterprise | | Matomo | ⭐⭐⭐⭐ | Free-$$$$ | 15 min | ✅ | Self-hosted | | Mixpanel | ⭐⭐⭐ | Free-$$$ | 10 min | ⚠️ | Product analytics | | Hotjar | ⭐⭐⭐ | Free-$$$ | 5 min | ⚠️ | User behavior | ## 1. Databuddy - Privacy-First Analytics ### Overview Databuddy is a modern, privacy-first analytics platform designed for businesses that prioritize user privacy without sacrificing insights. ### Key Features * **100% cookieless tracking** - No consent banners required * **Real-time analytics** - Instant data updates * **Core Web Vitals monitoring** - Built-in performance tracking * **AI-powered insights** - Automated recommendations * **Heatmaps & session recordings** - Visual user behavior analysis * **Form analytics** - Conversion optimization tools * **API-first design** - Easy integrations ### Pricing * **Starter**: $9/month (10K page views) * **Growth**: $29/month (100K page views) * **Business**: $99/month (1M page views) * **Enterprise**: Custom pricing ### Pros ✅ GDPR compliant by design ✅ No impact on site performance ✅ Accurate data (no ad-blocker issues) ✅ Modern, intuitive interface ✅ Excellent customer support ✅ All features included in every plan ### Cons ❌ Newer platform (less ecosystem) ❌ Not free (but 14-day trial) ### Best For * Privacy-conscious businesses * EU/UK companies needing GDPR compliance * Sites wanting accurate, unsampled data * Teams valuing customer support ## 2. Google Analytics - The Industry Standard ### Overview Google Analytics 4 (GA4) is the most widely used web analytics platform, offering comprehensive tracking and integration with Google's ecosystem. ### Key Features * **Free tier** - No cost for basic features * **Google Ads integration** - Seamless advertising workflow * **Advanced segments** - Complex audience analysis * **Attribution modeling** - Multi-touch attribution * **BigQuery export** - Data warehouse integration (360 only) * **Machine learning insights** - Automated anomaly detection ### Pricing * **GA4**: Free (10M events/month) * **GA4 360**: $150,000+/year ### Pros ✅ Free for most websites ✅ Extensive documentation and community ✅ Deep Google Ads integration ✅ Advanced analysis capabilities ✅ Mature ecosystem ### Cons ❌ Complex setup and learning curve ❌ GDPR compliance challenges ❌ Data sampling in free tier ❌ 30-50% data loss from ad blockers ❌ Your data becomes Google's product ### Best For * Google Ads heavy users * Large enterprises with dedicated analysts * Websites with complex attribution needs * Teams comfortable with data sharing ## 3. Adobe Analytics - Enterprise Powerhouse ### Overview Adobe Analytics is part of the Adobe Experience Cloud, designed for large enterprises with complex analytics needs. ### Key Features * **Real-time analytics** - Live data streaming * **Advanced segmentation** - Sophisticated audience analysis * **Attribution IQ** - Multiple attribution models * **Anomaly detection** - AI-powered insights * **Data Workbench** - Advanced data analysis * **Cross-device tracking** - Unified customer journeys ### Pricing * Custom pricing (typically $100,000+/year) * Quote-based on data volume and features ### Pros ✅ Extremely powerful and flexible ✅ Advanced analysis capabilities ✅ Enterprise-grade security ✅ Extensive customization options ✅ Professional services support ### Cons ❌ Very expensive ❌ Complex implementation ❌ Steep learning curve ❌ Requires dedicated analysts ❌ Privacy concerns with data collection ### Best For * Large enterprises ($100M+ revenue) * Companies with dedicated analytics teams * Complex multi-channel businesses * Organizations needing advanced customization ## 4. Matomo - Open Source Alternative ### Overview Matomo (formerly Piwik) is an open-source analytics platform that offers both self-hosted and cloud options. ### Key Features * **Open source** - Full control over your data * **Self-hosted option** - Keep data on your servers * **GDPR compliant** - Privacy-focused by design * **Heatmaps** - Visual user behavior analysis * **A/B testing** - Built-in experimentation * **Custom dimensions** - Flexible data collection ### Pricing * **Self-hosted**: Free (hosting costs apply) * **Cloud**: $23-$613/month based on traffic ### Pros ✅ Open source and transparent ✅ Full data ownership ✅ GDPR compliant ✅ No data sampling ✅ Extensive plugin ecosystem ### Cons ❌ Requires technical expertise for self-hosting ❌ Limited third-party integrations ❌ Interface feels dated ❌ Performance can be slow with large datasets ❌ Self-hosted maintenance overhead ### Best For * Technical teams comfortable with self-hosting * Organizations requiring full data control * Privacy-focused companies * Budget-conscious businesses ## 5. Mixpanel - Product Analytics Focus ### Overview Mixpanel specializes in product analytics, focusing on user actions and behaviors rather than traditional web analytics. ### Key Features * **Event-based tracking** - Track specific user actions * **Cohort analysis** - User retention insights * **Funnel analysis** - Conversion optimization * **A/B testing** - Built-in experimentation * **User profiles** - Individual user tracking * **Real-time data** - Live event streaming ### Pricing * **Free**: Up to 100K events/month * **Growth**: $25/month (100K events) * **Enterprise**: Custom pricing ### Pros ✅ Excellent for product analytics ✅ User-friendly interface ✅ Strong cohort and funnel analysis ✅ Good mobile app support ✅ Flexible event tracking ### Cons ❌ Not ideal for content websites ❌ Limited traditional web analytics features ❌ Can get expensive with high event volumes ❌ Privacy concerns with user tracking ❌ Complex setup for advanced features ### Best For * SaaS and mobile apps * Product managers and growth teams * Businesses focused on user engagement * Companies needing detailed user journey analysis ## 6. Hotjar - User Behavior Insights ### Overview Hotjar focuses on understanding user behavior through heatmaps, session recordings, and feedback tools. ### Key Features * **Heatmaps** - Click, move, and scroll tracking * **Session recordings** - Watch user interactions * **Conversion funnels** - Identify drop-off points * **Form analysis** - Optimize form completion * **Feedback polls** - Collect user opinions * **User interviews** - Recruit participants ### Pricing * **Basic**: Free (35 sessions/day) * **Plus**: $39/month (100 sessions/day) * **Business**: $99/month (500 sessions/day) * **Scale**: $213/month (unlimited) ### Pros ✅ Excellent user behavior insights ✅ Easy to implement and use ✅ Visual data representation ✅ Good for UX optimization ✅ Affordable pricing ### Cons ❌ Limited traditional analytics features ❌ Privacy concerns with recordings ❌ Can impact site performance ❌ GDPR compliance challenges ❌ Not suitable as primary analytics tool ### Best For * UX designers and researchers * E-commerce optimization * Understanding user behavior issues * Complementing traditional analytics ## Choosing the Right Analytics Tool ### Decision Framework #### 1. Privacy Requirements **High Privacy Needs:** * Databuddy (cookieless, GDPR compliant) * Matomo (self-hosted option) **Moderate Privacy:** * Mixpanel (with proper configuration) * Hotjar (with consent management) **Low Privacy Priority:** * Google Analytics * Adobe Analytics #### 2. Budget Considerations **Free Options:** * Google Analytics (with data trade-offs) * Matomo (self-hosted) * Mixpanel (limited free tier) **Budget-Friendly:** * Databuddy ($9-99/month) * Hotjar ($39-213/month) **Enterprise:** * Adobe Analytics ($100K+/year) * Google Analytics 360 ($150K+/year) #### 3. Technical Complexity **Simple Setup:** * Databuddy (2 minutes) * Hotjar (5 minutes) * Google Analytics (30 minutes) **Complex Implementation:** * Adobe Analytics * Matomo (self-hosted) * Advanced Mixpanel setups #### 4. Use Case Alignment **Content Websites:** * Databuddy * Google Analytics * Matomo **E-commerce:** * Databuddy * Google Analytics * Adobe Analytics **SaaS/Mobile Apps:** * Mixpanel * Databuddy * Adobe Analytics **UX Optimization:** * Hotjar * Databuddy (heatmaps included) ## 2024 Trends in Web Analytics ### 1. Privacy-First Analytics The shift toward cookieless tracking and privacy-compliant solutions is accelerating: * Third-party cookie deprecation * Stricter privacy regulations * User demand for transparency ### 2. Real-Time Insights Businesses need faster decision-making capabilities: * Live data streaming * Instant alerts and notifications * Real-time dashboard updates ### 3. AI-Powered Analytics Machine learning is becoming standard: * Automated insights and recommendations * Anomaly detection * Predictive analytics ### 4. Performance Monitoring Core Web Vitals and site performance are crucial: * Built-in performance tracking * SEO impact monitoring * User experience optimization ### 5. Integrated Platforms All-in-one solutions are preferred: * Analytics + heatmaps + A/B testing * Unified customer data platforms * Reduced tool sprawl ## Migration Guide ### From Google Analytics to Privacy-First Analytics #### Step 1: Audit Current Setup * Document existing goals and events * Export historical data * Identify key reports and dashboards #### Step 2: Choose Alternative Based on your needs: * **Privacy-first**: Databuddy * **Self-hosted**: Matomo * **Product focus**: Mixpanel #### Step 3: Parallel Implementation * Install new analytics alongside GA * Compare data for 30 days * Train team on new platform #### Step 4: Complete Migration * Remove Google Analytics code * Update privacy policy * Communicate changes to stakeholders ## Frequently Asked Questions ### Which analytics tool is most accurate? Privacy-first tools like Databuddy typically show 20-40% more traffic than Google Analytics due to ad-blocker resistance and no consent banner impact. ### Do I need consent banners with all analytics tools? No. Cookieless analytics like Databuddy don't require consent banners under GDPR. ### Can I use multiple analytics tools together? Yes, many businesses use complementary tools (e.g., Databuddy for privacy-compliant analytics + Hotjar for user behavior). ### What's the best free analytics alternative to Google Analytics? Matomo (self-hosted) is the best free alternative, though it requires technical setup and maintenance. ### How do I choose between different pricing tiers? Consider your monthly page views, required features, and team size. Most tools offer free trials to test before committing. ## Conclusion The best analytics tool for your business depends on your specific needs: * **For privacy-first businesses**: Databuddy offers the best balance of features, compliance, and ease of use * **For Google Ads users**: Google Analytics remains the most integrated option * **For enterprises**: Adobe Analytics provides the most advanced capabilities * **For self-hosting**: Matomo gives you complete control * **For product analytics**: Mixpanel excels at user behavior tracking * **For UX insights**: Hotjar provides excellent behavior visualization ### Our Recommendation For most businesses in 2024, **Databuddy** offers the best combination of: * Privacy compliance without complexity * Accurate, unsampled data * Modern features and interface * Excellent performance impact * Fair, transparent pricing Ready to try privacy-first analytics? [Start your free trial →](https://app.databuddy.cc/register) *** *Last updated: December 2024* file: ./content/docs/comparisons/databuddy-vs-google-analytics.mdx meta: { "title": "Databuddy vs Google Analytics: Complete Comparison 2025", "description": "Detailed comparison between Databuddy and Google Analytics. Learn about privacy, features, pricing, and which analytics tool is right for your business.", "icon": "BarChart3" } # Databuddy vs Google Analytics: Complete Comparison 2025 Choosing the right analytics platform is crucial for your business. This comprehensive comparison will help you understand the key differences between Databuddy and Google Analytics to make an informed decision. ## Quick Comparison Table | Feature | Databuddy | Google Analytics | | ------------------- | ------------------------------- | ---------------------------------- | | **Privacy** | 100% cookieless, GDPR compliant | Requires cookies, privacy concerns | | **Data Ownership** | You own all data | Google owns your data | | **Consent Banners** | Not required | Required in EU/UK | | **Real-time Data** | ✅ Instant | ✅ Yes | | **Custom Events** | ✅ Unlimited | ✅ Limited | | **API Access** | ✅ Full API | ✅ Limited API | | **Pricing** | Transparent, usage-based | Free with data trade-off | | **Setup Time** | \< 5 minutes | 30+ minutes | ## Privacy & Compliance ### Databuddy: Privacy-First Approach * **No cookies required** - Uses privacy-friendly tracking methods * **GDPR compliant by design** - No consent banners needed * **Data stays in EU Datacenters** - We are GDPR compliant * **No personal data collection** - Anonymous analytics only * **Full data ownership** - Export or delete anytime ### Google Analytics: Traditional Tracking * **Requires cookies** - Third-party cookies for cross-site tracking * **GDPR compliance challenges** - Requires consent management * **Data processed by Google** - Your data becomes Google's data * **Personal data collection** - IP addresses, user IDs stored * **Limited data portability** - Difficult to export historical data ## Features Comparison ### Core Analytics Features **Both platforms offer:** * Page views and sessions * Traffic sources and referrers * Device and browser analytics * Geographic data * Custom event tracking ### Databuddy Advantages * **Real-time data** - Instant data availability * **AI-powered insights** - Automated recommendations * **Performance monitoring** - Core Web Vitals tracking * **Error tracking** - JavaScript error monitoring * **Form analytics** - Conversion optimization tools * **API-first design** - Easy integrations ### Google Analytics Advantages * **Free tier** - No cost for basic features * **Google Ads integration** - Seamless advertising workflow * **Mature ecosystem** - Extensive third-party integrations * **Advanced segments** - Complex audience analysis * **Attribution modeling** - Multi-touch attribution ## Performance & Speed ### Databuddy * **Lightweight script** - Only 1KB gzipped * **Edge computing** - Global CDN for fast loading * **No impact on Core Web Vitals** - Privacy-first = performance-first * **Async loading** - Never blocks page rendering ### Google Analytics * **Larger script size** - 10KB+ with gtag * **Multiple requests** - Can slow down page load * **Cookie overhead** - Additional HTTP headers * **Potential CLS impact** - Can affect layout stability ## Pricing Comparison ### Databuddy Pricing * **Starter**: $9/month - Up to 50K page views * **Growth**: $29/month - Up to 100K page views * **Business**: $99/month - Up to 1M page views * **Enterprise**: Custom pricing for 1M+ page views **What's included:** * All features unlocked * Unlimited custom events * API access * Email support * Data export ### Google Analytics Pricing * **GA4 Free**: $0 - Up to 10M events/month * **GA4 360**: $150K+/year - Enterprise features **Hidden costs:** * Your data becomes Google's product * Privacy compliance costs (consent management) * Developer time for complex setup * Potential ad blocking (30%+ users block GA) ## Setup & Implementation ### Databuddy Setup ```html ``` **Setup time:** 2-5 minutes * Copy/paste one script tag * Verify domain ownership * Start collecting data immediately ### Google Analytics Setup ```html ``` **Setup time:** 30+ minutes * Create Google account * Set up GA4 property * Configure enhanced ecommerce * Set up conversion goals * Implement consent management ## Data Accuracy & Reliability ### Databuddy * **Ad-blocker resistant** - Server-side tracking options * **100% data collection** - No sampling * **Real-time processing** - Instant data availability * **Consistent tracking** - No cookie consent impact ### Google Analytics * **Ad-blocker impact** - 30-50% data loss * **Sampling in free tier** - Large datasets get sampled * **Consent impact** - 20-40% data loss in EU * **Processing delays** - 24-48 hour data processing ## Integration Capabilities ### Databuddy Integrations * **React/Next.js** - Native SDK * **WordPress** - Official plugin * **Shopify** - App store integration * **REST API** - Full programmatic access * **Webhooks** - Real-time data streaming * **Zapier** - 1000+ app connections ### Google Analytics Integrations * **Google Ads** - Native integration * **Google Search Console** - SEO data * **Google Tag Manager** - Tag management * **Data Studio** - Reporting dashboards * **BigQuery** - Data warehouse export (360 only) ## Which Should You Choose? ### Choose Databuddy If: * ✅ Privacy compliance is important * ✅ You want to own your data * ✅ You need accurate, unsampled data * ✅ You want fast, easy setup * ✅ You value customer support * ✅ You need modern features (heatmaps, performance monitoring) ### Choose Google Analytics If: * ✅ Budget is your primary concern * ✅ You heavily use Google Ads * ✅ You have complex attribution needs * ✅ You're comfortable with data sharing * ✅ You have dedicated analytics team ## Migration from Google Analytics Switching from Google Analytics to Databuddy is straightforward: 1. **Install Databuddy** - Add our script alongside GA 2. **Run in parallel** - Compare data for 30 days 3. **Configure events** - Match your existing tracking 4. **Remove Google Analytics** - Once you're confident 5. **Export historical data** - Before GA sunset dates ### Migration Checklist * [ ] Install Databuddy tracking code * [ ] Set up custom events * [ ] Configure conversion goals * [ ] Test data accuracy * [ ] Train team on new dashboard * [ ] Remove GA tracking code ## Frequently Asked Questions ### Is Databuddy GDPR compliant? Yes, Databuddy is GDPR compliant by design. We don't use cookies or collect personal data, so no consent banners are required. ### Can I use both Databuddy and Google Analytics? Absolutely! Many customers run both in parallel during migration or for different use cases. ### How accurate is Databuddy compared to GA? Databuddy typically shows 20-40% more traffic than GA due to ad-blocker resistance and no consent banner impact. ### Do you offer Google Analytics import? We're working on GA4 data import tools. Contact our team for early access. ## Get Started with Databuddy Ready to experience privacy-first analytics? Start your free trial today: * **14-day free trial** - No credit card required * **5-minute setup** - Be tracking in minutes * **Migration support** - Our team helps you switch * **Money-back guarantee** - 30 days, no questions asked [Start Free Trial →](https://app.databuddy.cc/register) *** *Last updated: December 2024* file: ./content/docs/compliance/gdpr-compliance-guide.mdx meta: { "title": "GDPR Compliance for Web Analytics: Complete Guide 2024", "description": "Everything you need to know about GDPR compliance for web analytics. Learn about consent requirements, data processing, and how to stay compliant while tracking website visitors.", "icon": "Shield" } # GDPR Compliance for Web Analytics: Complete Guide 2024 The General Data Protection Regulation (GDPR) has fundamentally changed how websites can track visitors. This comprehensive guide explains everything you need to know about GDPR compliance for web analytics. ## What is GDPR? The **General Data Protection Regulation (GDPR)** is a European Union law that came into effect on May 25, 2018. It regulates how organizations collect, process, and store personal data of EU residents. ### Key GDPR Principles 1. **Lawfulness, fairness, and transparency** 2. **Purpose limitation** - Data collected for specific purposes 3. **Data minimization** - Collect only necessary data 4. **Accuracy** - Keep data accurate and up-to-date 5. **Storage limitation** - Don't keep data longer than needed 6. **Integrity and confidentiality** - Secure data processing 7. **Accountability** - Demonstrate compliance ## GDPR and Web Analytics ### What Counts as Personal Data? Under GDPR, personal data includes any information that can identify a person: * ✅ **IP addresses** - Can identify location/ISP * ✅ **Cookie IDs** - Unique identifiers * ✅ **Device fingerprints** - Browser/device characteristics * ✅ **User IDs** - Account identifiers * ✅ **Email addresses** - Direct identifiers * ❌ **Aggregated statistics** - Cannot identify individuals * ❌ **Anonymous data** - Truly anonymized data ### Legal Basis for Processing To process personal data legally under GDPR, you need one of these legal bases: 1. **Consent** - User explicitly agrees 2. **Contract** - Necessary for service delivery 3. **Legal obligation** - Required by law 4. **Vital interests** - Life-or-death situations 5. **Public task** - Official authority functions 6. **Legitimate interests** - Balanced against user rights For web analytics, **consent** is typically the only viable legal basis. ## Traditional Analytics and GDPR Problems ### Google Analytics GDPR Issues **Data Processing Concerns:** * Transfers data to US servers * Uses personal identifiers (Client ID) * Processes IP addresses * Creates user profiles * Shares data with Google **Recent Legal Developments:** * Austrian DPA ruled GA illegal (2022) * French CNIL fined companies using GA * Italian DPA declared GA non-compliant * German DPAs issued warnings ### Common GDPR Violations 1. **No consent banner** - Processing without consent 2. **Pre-ticked boxes** - Invalid consent mechanism 3. **Forced consent** - Making consent mandatory for service 4. **Unclear purposes** - Vague consent language 5. **No opt-out** - Cannot withdraw consent easily 6. **Data transfers** - Sending data outside EU without safeguards ## GDPR-Compliant Analytics Solutions ### Option 1: Consent-Based Analytics **Requirements:** * Clear consent banners * Granular consent options * Easy consent withdrawal * Regular consent renewal * Consent management platform **Challenges:** * 20-40% consent rate in EU * Significant data loss * Complex implementation * Ongoing compliance burden * User experience impact ### Option 2: Privacy-First Analytics **Characteristics:** * No personal data collection * No cookies required * Anonymous tracking only * No consent banners needed * GDPR compliant by design **Benefits:** * 100% data collection * Better user experience * Simplified compliance * No consent fatigue * Future-proof solution ## How Databuddy Ensures GDPR Compliance ### Privacy by Design **No Personal Data Collection:** * No IP address storage * No user fingerprinting * No cross-site tracking * Anonymous aggregation only **Technical Safeguards:** * Data hashing at collection * Automatic data anonymization * No persistent identifiers * Edge processing for privacy * Minimal data retention ### Data Processing Transparency **What We Collect:** * Page URLs (without parameters) * Referrer information * Browser/device type * Geographic region (country/city) * Session duration * Custom events **What We Don't Collect:** * IP addresses * Personal identifiers * Cross-site data * Fingerprinted User Profiles ### Data Subject Rights Under GDPR, users have these rights: 1. **Right to information** - Know what data is processed 2. **Right of access** - Request copy of their data 3. **Right to rectification** - Correct inaccurate data 4. **Right to erasure** - Delete their data 5. **Right to restrict processing** - Limit data use 6. **Right to data portability** - Export their data 7. **Right to object** - Opt-out of processing **Databuddy's Approach:** Since we don't collect personal data, most rights don't apply. For any requests, we provide: * Clear data processing information * Easy contact for questions * Prompt response to requests * Data export capabilities ## Implementation Guide ### Step 1: Assess Current Analytics **Audit Questions:** * What analytics tools do you use? * What data do they collect? * Where is data processed? * Do you have consent mechanisms? * Are you compliant with current regulations? ### Step 2: Choose Compliance Strategy **Option A: Consent-Based Approach** ```html ``` **Option B: Privacy-First Approach** ```html ``` ### Step 3: Update Privacy Policy **Required Information:** * What data you collect * Why you collect it * How long you keep it * Who you share it with * User rights and contacts * Legal basis for processing **Example Privacy Policy Section:** ```markdown ## Website Analytics We use Databuddy for website analytics to understand how visitors use our site. **Data Collected:** - Pages visited - Time spent on site - Referrer information - Browser and device type - Geographic location (country/city level) **Legal Basis:** Legitimate interests in improving our website **Data Processing:** All data is anonymized and cannot identify individual users **Your Rights:** Contact us at privacy@yoursite.com for any questions ``` ### Step 4: Document Compliance **Required Documentation:** * Data processing records * Privacy impact assessments * Consent mechanisms (if used) * Data retention policies * Incident response procedures ## GDPR Compliance Checklist ### Legal Requirements * [ ] Identify legal basis for processing * [ ] Update privacy policy * [ ] Implement consent mechanisms (if needed) * [ ] Document data processing activities * [ ] Establish data subject request procedures * [ ] Appoint Data Protection Officer (if required) ### Technical Implementation * [ ] Audit current analytics tools * [ ] Implement privacy-compliant analytics * [ ] Remove non-compliant tracking * [ ] Set up data retention policies * [ ] Test consent mechanisms * [ ] Monitor compliance ongoing ### Organizational Measures * [ ] Train staff on GDPR requirements * [ ] Establish incident response procedures * [ ] Regular compliance reviews * [ ] Vendor compliance assessments * [ ] Data processing agreements ## Common GDPR Myths Debunked ### Myth 1: "GDPR only applies to EU companies" **Reality:** GDPR applies to any organization processing EU residents' data, regardless of location. ### Myth 2: "Anonymous data is always GDPR-exempt" **Reality:** Data must be truly anonymous. Pseudonymized data still falls under GDPR. ### Myth 3: "Legitimate interests always work for analytics" **Reality:** Legitimate interests must be balanced against user rights and may not apply to all analytics. ### Myth 4: "Small websites don't need to comply" **Reality:** GDPR applies to all organizations, regardless of size. ### Myth 5: "One-time consent is enough" **Reality:** Consent must be ongoing, specific, and easily withdrawable. ## Penalties and Enforcement ### GDPR Fines * **Tier 1:** Up to €10 million or 2% of annual turnover * **Tier 2:** Up to €20 million or 4% of annual turnover ### Recent Enforcement Actions * **Google (France):** €90 million for consent violations * **Amazon (Luxembourg):** €746 million for data processing * **WhatsApp (Ireland):** €225 million for transparency issues * **H\&M (Germany):** €35 million for employee monitoring ### Risk Factors * High-profile companies targeted first * Complaints trigger investigations * Cross-border cases get attention * Repeat offenders face higher fines ## Future of Privacy Regulations ### Emerging Regulations * **CCPA (California):** Similar to GDPR for California residents * **LGPD (Brazil):** Brazilian data protection law * **PIPEDA (Canada):** Updated privacy legislation * **UK GDPR:** Post-Brexit UK regulations ### Industry Trends * Third-party cookie deprecation * Privacy-first browser features * Increased user awareness * Regulatory enforcement growth ## Getting Started with Compliant Analytics ### Immediate Actions 1. **Audit current analytics** - Identify GDPR risks 2. **Switch to privacy-first analytics** - Implement Databuddy 3. **Update privacy policy** - Reflect new data practices 4. **Remove non-compliant tools** - Clean up tracking code 5. **Train your team** - Ensure ongoing compliance ### Migration Timeline * **Week 1:** Install Databuddy alongside existing analytics * **Week 2:** Compare data accuracy and completeness * **Week 3:** Update privacy policy and documentation * **Week 4:** Remove non-compliant analytics tools * **Ongoing:** Monitor compliance and regulations ## Frequently Asked Questions ### Do I need a consent banner with Databuddy? No, because Databuddy doesn't collect personal data, no consent banner is required under GDPR. ### Is server-side tracking GDPR compliant? It depends on what data you collect. Server-side tracking can still process personal data like IP addresses. ### Can I use Google Analytics and be GDPR compliant? It's challenging. You'd need explicit consent, proper data processing agreements, and may still face regulatory scrutiny. ### What about other privacy laws like CCPA? Databuddy's privacy-first approach helps with most privacy regulations, not just GDPR. ### How do I handle data subject requests? Since Databuddy doesn't collect personal data, most data subject rights don't apply. We provide clear information about our data practices. ## Conclusion GDPR compliance for web analytics doesn't have to be complicated. By choosing privacy-first analytics like Databuddy, you can: * ✅ Ensure full GDPR compliance * ✅ Collect 100% of your data * ✅ Provide better user experience * ✅ Future-proof your analytics * ✅ Reduce compliance burden Ready to simplify your GDPR compliance? [Start your free trial →](https://app.databuddy.cc/register) *** *This guide is for informational purposes only and does not constitute legal advice. Consult with a qualified attorney for specific legal guidance.* *Last updated: December 2024* file: ./content/docs/performance/core-web-vitals-guide.mdx meta: { "title": "Core Web Vitals Guide: Improve SEO & User Experience", "description": "Complete guide to Core Web Vitals - LCP, FID, and CLS. Learn how to measure, optimize, and monitor these crucial SEO ranking factors for better search performance.", "icon": "Zap" } # Core Web Vitals Guide: Improve SEO & User Experience Core Web Vitals are essential metrics that Google uses to evaluate user experience and SEO rankings. This comprehensive guide will help you understand, measure, and optimize these crucial performance indicators. ## What are Core Web Vitals? **Core Web Vitals** are a set of specific factors that Google considers important in a webpage's overall user experience. They are part of Google's "page experience" signals used in search ranking. ### The Three Core Web Vitals 1. **Largest Contentful Paint (LCP)** - Loading performance 2. **First Input Delay (FID)** - Interactivity 3. **Cumulative Layout Shift (CLS)** - Visual stability ## 1. Largest Contentful Paint (LCP) ### What is LCP? LCP measures how long it takes for the largest content element to become visible in the viewport. This could be: * Large images * Video elements * Block-level text elements * Background images ### LCP Thresholds * **Good:** 2.5 seconds or less * **Needs Improvement:** 2.5 to 4.0 seconds * **Poor:** More than 4.0 seconds ### How to Measure LCP **Using Databuddy:** ```javascript // Databuddy automatically tracks LCP databuddy.track('core_web_vital', { metric: 'LCP', value: lcpValue, element: lcpElement }); ``` **Using JavaScript:** ```javascript new PerformanceObserver((entryList) => { for (const entry of entryList.getEntries()) { console.log('LCP candidate:', entry.startTime, entry.element); } }).observe({entryTypes: ['largest-contentful-paint']}); ``` ### LCP Optimization Strategies #### 1. Optimize Images ```html Hero image ``` #### 2. Optimize Server Response Time * Use a Content Delivery Network (CDN) * Implement server-side caching * Optimize database queries * Use HTTP/2 or HTTP/3 #### 3. Remove Render-Blocking Resources ```html ``` #### 4. Optimize Critical Rendering Path ```html ``` ## 2. First Input Delay (FID) ### What is FID? FID measures the time from when a user first interacts with your page (clicks a link, taps a button) to when the browser actually begins processing that interaction. ### FID Thresholds * **Good:** 100 milliseconds or less * **Needs Improvement:** 100 to 300 milliseconds * **Poor:** More than 300 milliseconds ### How to Measure FID **Using Databuddy:** ```javascript // Databuddy tracks FID automatically databuddy.track('core_web_vital', { metric: 'FID', value: fidValue, eventType: eventType }); ``` **Using JavaScript:** ```javascript new PerformanceObserver((entryList) => { for (const entry of entryList.getEntries()) { const FID = entry.processingStart - entry.startTime; console.log('FID:', FID); } }).observe({entryTypes: ['first-input']}); ``` ### FID Optimization Strategies #### 1. Reduce JavaScript Execution Time ```javascript // Break up long tasks function processLargeArray(array) { const chunk = array.splice(0, 50); // Process chunk processChunk(chunk); if (array.length > 0) { // Continue processing in next frame setTimeout(() => processLargeArray(array), 0); } } ``` #### 2. Code Splitting ```javascript // Dynamic imports for code splitting const loadFeature = async () => { const { feature } = await import('./feature.js'); return feature; }; ``` #### 3. Web Workers for Heavy Tasks ```javascript // Move heavy computations to Web Workers const worker = new Worker('heavy-computation.js'); worker.postMessage(data); worker.onmessage = (event) => { console.log('Result:', event.data); }; ``` #### 4. Optimize Third-Party Scripts ```html ``` ## 3. Cumulative Layout Shift (CLS) ### What is CLS? CLS measures the sum of all individual layout shift scores for every unexpected layout shift that occurs during the entire lifespan of the page. ### CLS Thresholds * **Good:** 0.1 or less * **Needs Improvement:** 0.1 to 0.25 * **Poor:** More than 0.25 ### How to Measure CLS **Using Databuddy:** ```javascript // Databuddy tracks CLS automatically databuddy.track('core_web_vital', { metric: 'CLS', value: clsValue, sources: layoutShiftSources }); ``` **Using JavaScript:** ```javascript let clsValue = 0; new PerformanceObserver((entryList) => { for (const entry of entryList.getEntries()) { if (!entry.hadRecentInput) { clsValue += entry.value; console.log('Current CLS value:', clsValue, entry); } } }).observe({entryTypes: ['layout-shift']}); ``` ### CLS Optimization Strategies #### 1. Set Dimensions for Media ```html Description ``` #### 2. Reserve Space for Ads ```css .ad-container { min-height: 250px; /* Reserve space for ad */ background: #f0f0f0; /* Placeholder background */ } ``` #### 3. Avoid Inserting Content Above Existing Content ```javascript // Bad: Inserting content at the top document.body.insertBefore(newElement, document.body.firstChild); // Good: Append to the end or use fixed positioning document.body.appendChild(newElement); ``` #### 4. Use CSS Transform for Animations ```css /* Bad: Animating layout properties */ .element { transition: width 0.3s; } /* Good: Animating transform properties */ .element { transition: transform 0.3s; } ``` ## Core Web Vitals and SEO ### Google's Page Experience Update Since June 2021, Core Web Vitals are official Google ranking factors: * **Direct ranking impact** - Poor vitals can hurt rankings * **Mobile-first indexing** - Mobile vitals are prioritized * **User experience signals** - Combined with other UX factors * **Competitive advantage** - Good vitals can boost rankings ### SEO Impact Analysis ```javascript // Track Core Web Vitals impact on SEO databuddy.track('seo_performance', { lcp: lcpValue, fid: fidValue, cls: clsValue, searchRanking: currentRanking, organicTraffic: trafficData }); ``` ## Monitoring Core Web Vitals ### Real User Monitoring (RUM) Monitor actual user experiences: ```javascript // Databuddy provides automatic RUM databuddy.init({ clientId: 'your-client-id', trackPerformance: true, // Enables Core Web Vitals tracking trackErrors: true, trackScreenViews: true }); ``` ### Lab Testing Tools * **Google PageSpeed Insights** - Free Google tool * **Lighthouse** - Built into Chrome DevTools * **WebPageTest** - Detailed performance analysis * **GTmetrix** - Performance monitoring service ### Continuous Monitoring Setup #### 1. Automated Testing ```yaml # GitHub Actions example name: Performance Testing on: [push, pull_request] jobs: lighthouse: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Run Lighthouse CI run: | npm install -g @lhci/cli lhci autorun ``` #### 2. Performance Budgets ```json { "budgets": [{ "path": "/*", "timings": [{ "metric": "largest-contentful-paint", "budget": 2500 }, { "metric": "cumulative-layout-shift", "budget": 0.1 }] }] } ``` ## Analytics Impact on Core Web Vitals ### Traditional Analytics Problems Many analytics tools negatively impact Core Web Vitals: * **Large script sizes** - Increase LCP * **Blocking JavaScript** - Worsen FID * **Dynamic content injection** - Cause CLS * **Third-party requests** - Slow loading ### Databuddy's Performance Advantage #### Minimal Impact on Core Web Vitals ```javascript // Lightweight, async loading ``` **Performance Benefits:** * **2KB gzipped** - Minimal script size * **Async loading** - No render blocking * **Edge CDN** - Fast global delivery * **No layout shifts** - Stable tracking * **Performance monitoring** - Built-in Core Web Vitals tracking ## Optimization Checklist ### LCP Optimization * [ ] Optimize images (WebP, AVIF formats) * [ ] Implement lazy loading for below-fold images * [ ] Use preload for critical resources * [ ] Minimize server response time * [ ] Remove render-blocking resources * [ ] Use a CDN for static assets ### FID Optimization * [ ] Minimize JavaScript execution time * [ ] Implement code splitting * [ ] Use Web Workers for heavy tasks * [ ] Defer non-critical JavaScript * [ ] Optimize third-party scripts * [ ] Remove unused JavaScript ### CLS Optimization * [ ] Set dimensions for all images and videos * [ ] Reserve space for ads and embeds * [ ] Avoid inserting content above existing content * [ ] Use CSS transforms for animations * [ ] Preload fonts to prevent FOIT/FOUT * [ ] Test dynamic content loading ## Common Core Web Vitals Issues ### Issue 1: Large Images Causing Poor LCP **Problem:** Unoptimized hero images **Solution:** ```html Hero ``` ### Issue 2: Third-Party Scripts Blocking FID **Problem:** Synchronous third-party scripts **Solution:** ```html ``` ### Issue 3: Dynamic Content Causing CLS **Problem:** Content loading without reserved space **Solution:** ```css .dynamic-content { min-height: 200px; /* Reserve space */ background: linear-gradient(90deg, #f0f0f0 25%, transparent 25%); background-size: 20px 20px; animation: loading 1s infinite linear; } @keyframes loading { 0% { background-position: 0 0; } 100% { background-position: 20px 0; } } ``` ## Advanced Optimization Techniques ### 1. Resource Prioritization ```html ``` ### 2. Service Worker Optimization ```javascript // Cache critical resources self.addEventListener('install', (event) => { event.waitUntil( caches.open('v1').then((cache) => { return cache.addAll([ '/critical.css', '/hero.jpg', '/app.js' ]); }) ); }); ``` ### 3. Progressive Enhancement ```javascript // Load features progressively if ('IntersectionObserver' in window) { // Use modern lazy loading lazyLoadImages(); } else { // Fallback for older browsers loadAllImages(); } ``` ## Measuring Success ### Key Performance Indicators Track these metrics to measure Core Web Vitals improvement: * **Core Web Vitals scores** - LCP, FID, CLS values * **Search rankings** - Position changes for target keywords * **Organic traffic** - Search engine traffic growth * **User engagement** - Bounce rate, time on page * **Conversion rates** - Goal completions, sales ### Reporting Dashboard ```javascript // Track performance improvements databuddy.track('performance_improvement', { beforeLCP: 3.2, afterLCP: 2.1, beforeFID: 150, afterFID: 80, beforeCLS: 0.25, afterCLS: 0.08, trafficIncrease: '15%', rankingImprovement: 3 }); ``` ## Conclusion Core Web Vitals are crucial for both SEO and user experience. By following this guide, you can: * ✅ Understand what Core Web Vitals measure * ✅ Implement effective optimization strategies * ✅ Monitor performance continuously * ✅ Improve search rankings and user satisfaction * ✅ Use analytics that don't hurt performance Ready to optimize your Core Web Vitals? Databuddy provides built-in performance monitoring without impacting your scores. [Start monitoring your Core Web Vitals →](https://app.databuddy.cc/register) *** *Last updated: June 2025* file: ./content/docs/privacy/cookieless-analytics-guide.mdx meta: { "title": "Cookieless Analytics: Complete Guide to Privacy-First Tracking", "description": "Learn how cookieless analytics works, why it's the future of web tracking, and how to implement privacy-first analytics without compromising on insights.", "icon": "Shield" } # Cookieless Analytics: Complete Guide to Privacy-First Tracking The era of third-party cookies is ending. This comprehensive guide explains cookieless analytics, why it matters, and how to implement privacy-first tracking that respects user privacy while delivering powerful insights. ## What is Cookieless Analytics? **Cookieless analytics** refers to web analytics methods that don't rely on cookies to track user behavior. Instead, they use privacy-friendly techniques to collect anonymous, aggregated data about website visitors. ### Traditional Cookie-Based Tracking ```javascript // Traditional approach - uses cookies document.cookie = "user_id=12345; expires=Thu, 18 Dec 2025 12:00:00 UTC; path=/"; ga('create', 'UA-XXXXX-Y', 'auto'); ga('send', 'pageview'); ``` ### Cookieless Tracking Approach ```javascript // Cookieless approach - no persistent identifiers databuddy.track('page_view', { page: window.location.pathname, referrer: document.referrer, // No user ID or persistent tracking }); ``` ## Why Cookieless Analytics Matters ### 1. Privacy Regulations **GDPR, CCPA, and Beyond:** * Third-party cookies require explicit consent * Heavy fines for non-compliance (up to 4% of revenue) * Growing number of privacy laws worldwide ### 2. Browser Changes **Major Browser Updates:** * **Safari**: Blocks third-party cookies by default * **Firefox**: Enhanced Tracking Protection enabled * **Chrome**: Phasing out third-party cookies by 2024 * **Edge**: Following Chrome's timeline ### 3. User Expectations **Changing User Behavior:** * 86% of users care about data privacy * 79% willing to switch brands over privacy concerns * Ad blocker usage continues to grow (30%+ of users) ### 4. Data Accuracy **Better Data Quality:** * No consent banner impact (20-40% data loss) * Ad-blocker resistant tracking * Consistent cross-browser behavior * No cookie expiration issues ## How Cookieless Analytics Works ### 1. Server-Side Tracking Instead of client-side cookies, data is processed on the server: ```javascript // Client sends minimal data fetch('/analytics/track', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ event: 'page_view', page: location.pathname, referrer: document.referrer }) }); ``` ### 2. Fingerprinting-Free Identification Uses non-invasive methods to understand user sessions: ```javascript // Session-based tracking without fingerprinting const sessionData = { timestamp: Date.now(), viewport: `${window.innerWidth}x${window.innerHeight}`, language: navigator.language, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone }; ``` ### 3. Privacy-Safe Aggregation Data is immediately anonymized and aggregated: ```javascript // Server-side aggregation const pageStats = { url: '/products', views: 1247, unique_sessions: 892, avg_time: 145, // seconds bounce_rate: 0.34 }; ``` ## Cookieless Analytics Techniques ### 1. First-Party Data Collection Collect data directly from your own domain: ```html ``` **Benefits:** * No third-party cookie restrictions * Better performance and reliability * Full control over data collection ### 2. Session-Based Tracking Track user sessions without persistent identifiers: ```javascript // Generate session ID (not stored as cookie) const sessionId = crypto.randomUUID(); const sessionStart = Date.now(); // Track session events function trackEvent(event, data) { sendToServer({ session: sessionId, timestamp: Date.now(), event: event, data: data }); } ``` ### 3. Statistical Modeling Use statistical methods to understand user behavior: ```javascript // Cohort analysis without individual tracking const cohortData = { week: '2024-W01', new_users: 1250, returning_users: 3400, retention_rate: 0.68 }; ``` ### 4. Privacy-Safe Attribution Track conversions without cross-site tracking: ```javascript // Attribution without cookies const attribution = { source: 'organic_search', medium: 'google', campaign: null, conversion_value: 99.99, time_to_conversion: 3600 // seconds }; ``` ## Implementing Cookieless Analytics ### Option 1: Databuddy (Recommended) Complete cookieless solution with full features: ```html ``` **Features:** * 100% cookieless by design * Real-time analytics * GDPR compliant * No consent banners required * Full feature set (heatmaps, funnels, etc.) ### Option 2: Custom Implementation Build your own cookieless tracking: ```javascript // Custom cookieless tracker class CookielessAnalytics { constructor(endpoint) { this.endpoint = endpoint; this.sessionId = this.generateSessionId(); this.startTime = Date.now(); } generateSessionId() { return Date.now().toString(36) + Math.random().toString(36).substr(2); } track(event, properties = {}) { const data = { session_id: this.sessionId, event: event, properties: { ...properties, timestamp: Date.now(), page: location.pathname, referrer: document.referrer, user_agent: navigator.userAgent, screen_resolution: `${screen.width}x${screen.height}`, viewport: `${window.innerWidth}x${window.innerHeight}`, language: navigator.language, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone } }; // Send to server fetch(this.endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), keepalive: true }); } trackPageView() { this.track('page_view'); } trackEvent(name, properties) { this.track('custom_event', { name, ...properties }); } } // Usage const analytics = new CookielessAnalytics('/api/analytics'); analytics.trackPageView(); ``` ### Option 3: Server-Side Google Analytics Use GA4 Measurement Protocol (limited features): ```javascript // Server-side GA4 tracking const measurementId = 'G-XXXXXXXXXX'; const apiSecret = 'your-api-secret'; function trackServerSide(clientId, events) { fetch(`https://www.google-analytics.com/mp/collect?measurement_id=${measurementId}&api_secret=${apiSecret}`, { method: 'POST', body: JSON.stringify({ client_id: clientId, events: events }) }); } ``` ## Cookieless Analytics Features ### 1. Page Views and Sessions Track basic website metrics: ```javascript // Page view tracking databuddy.track('page_view', { page: location.pathname, title: document.title, referrer: document.referrer }); // Session tracking databuddy.track('session_start', { entry_page: location.pathname, traffic_source: getTrafficSource() }); ``` ### 2. User Engagement Measure user interaction without personal data: ```javascript // Scroll tracking let maxScroll = 0; window.addEventListener('scroll', () => { const scrollPercent = Math.round((window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100); if (scrollPercent > maxScroll) { maxScroll = scrollPercent; databuddy.track('scroll_depth', { percent: scrollPercent }); } }); // Time on page let startTime = Date.now(); window.addEventListener('beforeunload', () => { const timeOnPage = Date.now() - startTime; databuddy.track('time_on_page', { duration: timeOnPage }); }); ``` ### 3. Conversion Tracking Track goals and conversions: ```javascript // E-commerce tracking function trackPurchase(orderData) { databuddy.track('purchase', { value: orderData.total, currency: 'USD', items: orderData.items.length, // No personal information }); } // Form submissions document.querySelector('#contact-form').addEventListener('submit', () => { databuddy.track('form_submit', { form_name: 'contact', page: location.pathname }); }); ``` ### 4. Performance Monitoring Track Core Web Vitals and performance: ```javascript // Core Web Vitals tracking new PerformanceObserver((entryList) => { for (const entry of entryList.getEntries()) { databuddy.track('core_web_vital', { metric: entry.entryType, value: entry.value || entry.startTime, page: location.pathname }); } }).observe({ entryTypes: ['largest-contentful-paint', 'first-input', 'layout-shift'] }); ``` ## Benefits of Cookieless Analytics ### 1. Privacy Compliance * **No consent banners required** * **GDPR/CCPA compliant by design** * **Respects user privacy preferences** * **Reduces legal compliance burden** ### 2. Better Data Quality * **No ad-blocker interference** * **Consistent cross-browser tracking** * **No cookie expiration issues** * **Higher data accuracy (20-40% more data)** ### 3. Improved Performance * **Faster page load times** * **Reduced third-party requests** * **Better Core Web Vitals scores** * **Enhanced user experience** ### 4. Future-Proof Solution * **Works without third-party cookies** * **Compatible with privacy browsers** * **Adapts to changing regulations** * **Sustainable long-term approach** ## Challenges and Solutions ### Challenge 1: Cross-Device Tracking **Problem:** Can't track users across devices without cookies **Solution:** Focus on session-based insights and statistical modeling ### Challenge 2: Attribution Modeling **Problem:** Limited ability to track multi-touch attribution **Solution:** Use first-party data and probabilistic attribution ### Challenge 3: Audience Segmentation **Problem:** Can't create persistent user segments **Solution:** Use behavioral patterns and cohort analysis ### Challenge 4: Retargeting **Problem:** Can't retarget specific users **Solution:** Focus on contextual advertising and lookalike audiences ## Cookieless Analytics Best Practices ### 1. Data Minimization Collect only necessary data: ```javascript // Good: Minimal data collection const eventData = { event: 'page_view', page: location.pathname, referrer: document.referrer }; // Avoid: Excessive data collection const excessiveData = { event: 'page_view', user_agent: navigator.userAgent, screen_resolution: screen.width + 'x' + screen.height, installed_plugins: navigator.plugins, // ... too much data }; ``` ### 2. Transparent Data Practices Be clear about data collection: ```html
We use cookieless analytics to understand how visitors use our site. No personal data is collected or stored. Learn more
``` ### 3. Regular Data Audits Monitor your data collection: ```javascript // Audit data collection function auditDataCollection() { console.log('Data collected:', { personal_data: false, cookies_used: false, third_party_requests: 0, data_retention: '90 days' }); } ``` ### 4. Performance Monitoring Ensure analytics don't impact performance: ```javascript // Monitor analytics performance const observer = new PerformanceObserver((list) => { for (const entry of list.getEntries()) { if (entry.name.includes('analytics')) { console.log('Analytics performance:', entry.duration); } } }); observer.observe({ entryTypes: ['resource'] }); ``` ## Migration to Cookieless Analytics ### Step 1: Audit Current Setup * Identify all tracking cookies * Document data collection practices * Assess GDPR compliance gaps * Review third-party integrations ### Step 2: Choose Cookieless Solution * **Databuddy**: Full-featured, easy migration * **Custom solution**: Maximum control, requires development * **Server-side GA4**: Limited features, complex setup ### Step 3: Implement Parallel Tracking ```html ``` ### Step 4: Compare and Validate * Compare data accuracy * Validate key metrics * Test all tracking scenarios * Train team on new platform ### Step 5: Complete Migration * Remove cookie-based tracking * Update privacy policy * Remove consent banners * Monitor performance ## Future of Cookieless Analytics ### Emerging Technologies * **Privacy Sandbox**: Google's cookie alternatives * **Server-side tracking**: Increased adoption * **AI-powered insights**: Better data analysis * **Edge computing**: Faster, more private processing ### Industry Trends * **Privacy-first design**: Default approach * **Regulatory expansion**: More privacy laws * **Browser evolution**: Enhanced privacy features * **User expectations**: Greater privacy awareness ## Frequently Asked Questions ### Is cookieless analytics as accurate as cookie-based tracking? Often more accurate due to no ad-blocker interference and consent banner impact. ### Can I still track conversions without cookies? Yes, using first-party data and session-based attribution methods. ### Do I need consent banners with cookieless analytics? No, if no personal data is collected, consent banners aren't required under GDPR. ### How does cookieless analytics handle returning visitors? Uses statistical modeling and behavioral patterns instead of individual tracking. ### Can I integrate cookieless analytics with advertising platforms? Yes, through server-side integrations and first-party data sharing. ## Conclusion Cookieless analytics represents the future of web tracking. By adopting privacy-first analytics now, you can: * ✅ Ensure regulatory compliance * ✅ Improve data accuracy and quality * ✅ Enhance website performance * ✅ Build user trust and loyalty * ✅ Future-proof your analytics strategy Ready to go cookieless? Databuddy makes the transition simple and seamless. [Start your cookieless analytics journey →](https://app.databuddy.cc/register) *** *Last updated: June 2025*