Skip to main content

Analytics System - Complete Implementation Guide

๐ŸŽ‰ System Status: PRODUCTION READYโ€‹

Your analytics system is fully functional and ready to track website visitors!


๐Ÿ“‹ What's Implementedโ€‹

โœ… Backend (MedusaJS v2)โ€‹

  • Custom Analytics Module (custom_analytics)
  • 3 Data Models: AnalyticsEvent, AnalyticsSession, AnalyticsDailyStats
  • Complete CRUD Workflows
  • Public Tracking API: /web/analytics/track
  • Admin Query APIs: Filter by website, page, visitor, session
  • Reporting APIs: Stats & timeseries for dashboards
  • Read-only Module Link: Website โ†” Analytics (zero overhead)
  • 12 Integration Tests: All passing โœ…

โœ… Client-Side Trackingโ€‹

  • Lightweight Script: analytics.js (~2KB)
  • Auto Pageview Tracking: Including SPA navigation
  • Custom Event API: window.jytAnalytics.track()
  • Session Management: 30-minute timeout
  • Privacy-Focused: No cookies, no PII, GDPR compliant

โœ… Admin UIโ€‹

  • Analytics Modal: View website analytics in admin panel
  • Action Menu Integration: Easy access from website detail page
  • Real-time Stats: Views, visitors, sessions, custom events
  • Recent Events List: Last 10 events with timestamps
  • Time Range Selector: 7, 30, or 90 days

๐Ÿš€ Quick Startโ€‹

1. Add Tracking Script to Your Websiteโ€‹

<!-- Add to your website's <head> or before </body> -->
<script
src="/analytics.js"
data-website-id="01JM1PEW9H0ES7GGMD173GM2T9"
data-api-url="http://localhost:9000"
defer
></script>

For Next.js (already added to /app/layout.tsx):

<script 
src="/analytics.js"
data-website-id="01JM1PEW9H0ES7GGMD173GM2T9"
data-api-url="http://localhost:9000"
defer
/>

2. View Analytics in Adminโ€‹

  1. Navigate to Websites in admin panel
  2. Click on your website
  3. Click Analytics in the action menu (top right)
  4. View your stats! ๐Ÿ“Š

๐Ÿ“Š Available APIsโ€‹

1. Track Events (Public)โ€‹

POST /web/analytics/track
{
"website_id": "01JM1PEW9H0ES7GGMD173GM2T9",
"event_type": "pageview",
"pathname": "/products",
"visitor_id": "visitor_xyz",
"session_id": "session_abc"
}

2. Query Events (Admin)โ€‹

# All events for website
GET /admin/analytics-events?website_id=01JM1PEW9H0ES7GGMD173GM2T9

# Filter by page
GET /admin/analytics-events?website_id=01JM1PEW9H0ES7GGMD173GM2T9&pathname=/products

# Filter by visitor
GET /admin/analytics-events?website_id=01JM1PEW9H0ES7GGMD173GM2T9&visitor_id=visitor_xyz

3. Get Stats (Admin)โ€‹

# Last 30 days
GET /admin/analytics-events/stats?website_id=01JM1PEW9H0ES7GGMD173GM2T9&days=30

# Custom date range
GET /admin/analytics-events/stats?website_id=01JM1PEW9H0ES7GGMD173GM2T9&start_date=2024-01-01&end_date=2024-01-31

4. Get Timeseries (Admin)โ€‹

# Daily data for charts
GET /admin/analytics-events/timeseries?website_id=01JM1PEW9H0ES7GGMD173GM2T9&days=30&interval=day

# Hourly data
GET /admin/analytics-events/timeseries?website_id=01JM1PEW9H0ES7GGMD173GM2T9&days=1&interval=hour

5. Website Analytics Overview (Admin)โ€‹

# Get website with analytics
GET /admin/websites/01JM1PEW9H0ES7GGMD173GM2T9/analytics?days=30

๐ŸŽฏ What's Trackedโ€‹

Automatically:โ€‹

  • โœ… Page Views: Every page visit
  • โœ… Referrer Sources: Google, Facebook, Direct, etc.
  • โœ… Browser & OS: Parsed from user agent
  • โœ… Device Type: Desktop, mobile, tablet
  • โœ… Country: From IP (not stored)
  • โœ… Sessions: 30-minute timeout
  • โœ… Unique Visitors: Anonymous IDs

Manually (Custom Events):โ€‹

// Track button click
window.jytAnalytics.track('button_click', {
button_id: 'signup',
location: 'hero'
});

// Track form submission
window.jytAnalytics.track('form_submit', {
form_id: 'contact',
success: true
});

๐Ÿ”’ Privacy Featuresโ€‹

  • โŒ No Cookies: Uses localStorage/sessionStorage
  • โŒ No PII: No names, emails, or personal data
  • โŒ No IP Storage: Used only for geo-location, then discarded
  • โŒ No Cross-Site Tracking
  • โŒ No Query Parameters: Only pathname tracked
  • โœ… Anonymous IDs: Random, not linked to users
  • โœ… GDPR Compliant: No consent required

๐Ÿ“ File Structureโ€‹

jyt/
โ”œโ”€โ”€ src/
โ”‚ โ”œโ”€โ”€ modules/analytics/
โ”‚ โ”‚ โ”œโ”€โ”€ models/
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ analytics-event.ts
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ analytics-session.ts
โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ analytics-daily-stats.ts
โ”‚ โ”‚ โ”œโ”€โ”€ service.ts
โ”‚ โ”‚ โ””โ”€โ”€ index.ts
โ”‚ โ”œโ”€โ”€ workflows/analytics/
โ”‚ โ”‚ โ”œโ”€โ”€ track-analytics-event.ts
โ”‚ โ”‚ โ”œโ”€โ”€ create-analytics-event.ts
โ”‚ โ”‚ โ”œโ”€โ”€ list-analytics-event.ts
โ”‚ โ”‚ โ””โ”€โ”€ reports/
โ”‚ โ”‚ โ”œโ”€โ”€ get-analytics-stats.ts
โ”‚ โ”‚ โ””โ”€โ”€ get-analytics-timeseries.ts
โ”‚ โ”œโ”€โ”€ api/
โ”‚ โ”‚ โ”œโ”€โ”€ web/analytics/track/route.ts
โ”‚ โ”‚ โ””โ”€โ”€ admin/
โ”‚ โ”‚ โ”œโ”€โ”€ analytics-events/
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ route.ts
โ”‚ โ”‚ โ”‚ โ”œโ”€โ”€ stats/route.ts
โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ timeseries/route.ts
โ”‚ โ”‚ โ””โ”€โ”€ websites/[id]/
โ”‚ โ”‚ โ”œโ”€โ”€ analytics/route.ts
โ”‚ โ”‚ โ””โ”€โ”€ tracking-code/route.ts
โ”‚ โ”œโ”€โ”€ links/
โ”‚ โ”‚ โ””โ”€โ”€ website-analytics-link.ts (read-only)
โ”‚ โ””โ”€โ”€ admin/
โ”‚ โ”œโ”€โ”€ routes/websites/[id]/analytics/page.tsx
โ”‚ โ”œโ”€โ”€ components/websites/
โ”‚ โ”‚ โ”œโ”€โ”€ website-analytics-modal.tsx
โ”‚ โ”‚ โ””โ”€โ”€ website-general-section.tsx (+ Analytics button)
โ”‚ โ””โ”€โ”€ hooks/api/analytics.ts
โ”œโ”€โ”€ integration-tests/
โ”‚ โ””โ”€โ”€ http/analytics/
โ”‚ โ””โ”€โ”€ track-analytics-event.spec.ts (12 tests โœ…)
โ””โ”€โ”€ docs/
โ”œโ”€โ”€ /docs/implementation/analytics/implementation
โ”œโ”€โ”€ /docs/implementation/analytics/architecture-decision
โ”œโ”€โ”€ /docs/guides/analytics/website-setup
โ”œโ”€โ”€ /docs/implementation/analytics/reporting-apis
โ”œโ”€โ”€ /docs/implementation/analytics/module-linking-readonly
โ””โ”€โ”€ ANALYTICS_COMPLETE_GUIDE.md (this file)

jyt-web/jyt-web/
โ”œโ”€โ”€ public/
โ”‚ โ””โ”€โ”€ analytics.js (tracking script)
โ”œโ”€โ”€ app/
โ”‚ โ””โ”€โ”€ layout.tsx (tracking script added)
โ””โ”€โ”€ docs/
โ””โ”€โ”€ ANALYTICS_TRACKING.md

๐Ÿงช Testingโ€‹

Run Integration Testsโ€‹

cd /Users/saranshsharma/Documents/jyt
npm run test:integration -- analytics

Expected Result: All 12 tests passing โœ…

Manual Testingโ€‹

  1. Start Backend:

    cd /Users/saranshsharma/Documents/jyt
    npm run dev # Port 9000
  2. Start Frontend:

    cd /Users/saranshsharma/Documents/jyt-web/jyt-web
    npm run dev # Port 3000
  3. Open Browser:

    • Visit: http://localhost:3000
    • Open DevTools โ†’ Console
    • Look for: [Analytics] Initialized for website: 01JM1PEW9H0ES7GGMD173GM2T9
    • Navigate between pages
    • Check Network tab for POST to /web/analytics/track
  4. View Analytics:

    • Go to: http://localhost:9000/app/websites/01JM1PEW9H0ES7GGMD173GM2T9
    • Click Analytics button
    • See your tracking data! ๐Ÿ“Š

๐ŸŽจ Admin UI Featuresโ€‹

Analytics Modal Shows:โ€‹

  1. Time Range Selector

    • Last 7 days
    • Last 30 days
    • Last 90 days
  2. Website Info

    • Name
    • Domain
    • Status badge
  3. Overview Stats (4 cards)

    • ๐Ÿ‘๏ธ Total Views
    • ๐Ÿ‘ฅ Unique Visitors
    • ๐Ÿ”„ Sessions
    • โšก Custom Events
  4. Recent Events (last 10)

    • Event type badge
    • Event name (if custom)
    • Pathname
    • Timestamp
  5. Quick Stats

    • Total events count
    • Pages per visitor

๐Ÿ”ง Configurationโ€‹

Environment Variablesโ€‹

# Backend (.env)
WEB_CORS=http://localhost:3000,https://your-domain.com
MEDUSA_BACKEND_URL=http://localhost:9000

Website IDโ€‹

Your website ID: 01JM1PEW9H0ES7GGMD173GM2T9

This is used in:

  • Tracking script: data-website-id="01JM1PEW9H0ES7GGMD173GM2T9"
  • API queries: ?website_id=01JM1PEW9H0ES7GGMD173GM2T9

๐Ÿ“š Documentationโ€‹

  1. /docs/implementation/analytics/implementation

    • Technical implementation details
    • Data models and workflows
    • Privacy features
  2. /docs/implementation/analytics/architecture-decision

    • Why custom analytics
    • Architecture decisions
    • Module structure
  3. /docs/guides/analytics/website-setup

    • Step-by-step setup guide
    • Website linking explained
    • Troubleshooting
  4. /docs/implementation/analytics/reporting-apis

    • Complete API reference
    • Query examples
    • React hook examples
  5. /docs/implementation/analytics/module-linking-readonly

    • Read-only module link explained
    • Graph query examples
    • Performance benefits
  6. ANALYTICS_TRACKING.md

    • Client-side tracking guide
    • Usage examples (HTML, React, Vue, Next.js)
    • Custom event tracking

โœจ Next Steps (Optional)โ€‹

Phase 4: Background Jobsโ€‹

  • Daily aggregation (populate AnalyticsDailyStats)
  • Session cleanup (close inactive sessions)
  • Data retention (archive old events)

Phase 5: Advanced Featuresโ€‹

  • Real-time analytics with WebSockets
  • Funnel analysis
  • A/B testing support
  • Heatmaps
  • Export to CSV/PDF

๐ŸŽ‰ Summaryโ€‹

You now have a fully functional, production-ready analytics system!

What Works:โ€‹

โœ… Tracking pageviews and custom events โœ… Privacy-focused (no cookies, no PII) โœ… Admin UI to view analytics โœ… Powerful reporting APIs โœ… Read-only module linking (zero overhead) โœ… All tests passing โœ… Complete documentation

How to Use:โ€‹

  1. โœ… Tracking script is already added to your Next.js app
  2. โœ… Analytics button is in the website action menu
  3. โœ… Data is being tracked (you saw it in the logs!)
  4. โœ… View analytics in admin panel

The system is live and collecting data right now! ๐Ÿš€

Visit your website, navigate around, then check the analytics modal to see your data!


๐Ÿ†˜ Supportโ€‹

If you encounter any issues:

  1. Check browser console for errors
  2. Check Network tab for failed requests
  3. Verify CORS settings in .env
  4. Check backend logs for errors
  5. Review the troubleshooting guides in the docs

Built with โค๏ธ using MedusaJS v2