Analytics Plugin

Built-in analytics and insights for SonicJS with page view tracking, user sessions, custom events, real-time monitoring, and detailed reporting.


Overview

The Analytics plugin provides comprehensive visitor and content analytics without requiring external services. Track page views, user behavior, and custom events directly within your SonicJS application.

📊

Page View Tracking

Automatic tracking of all page visits with referrer and user agent data

👥

Session Management

Track user sessions with duration and behavior patterns

Real-time Analytics

Monitor active users and live page activity

📈

Custom Reports

Generate detailed reports with custom date ranges


Features

Automatic Tracking

  • Page views tracked automatically via middleware
  • Request method, status, and duration captured
  • User agent and referrer recorded
  • IP address tracking (from Cloudflare headers)

Session Analytics

  • Unique session IDs per visitor
  • Session duration tracking
  • User behavior patterns
  • Bounce rate calculation

Custom Events

  • Track any custom event type
  • Associate events with users and sessions
  • Store event metadata as JSON
  • Query events by type or time range

Reporting

  • Traffic reports by date range
  • Top pages by views
  • User engagement metrics
  • Export capabilities

Setup

The Analytics plugin is included with SonicJS core and enabled by default.

Verify Plugin Status

Navigate to Admin > Plugins to confirm the Analytics plugin is active.

Database Tables

The plugin automatically creates these tables:

TablePurpose
analytics_pageviewsStores page view records
analytics_eventsStores custom event data

Tracking Page Views

Page views are tracked automatically by the analytics middleware. Each request captures:

Page View Data

interface PageView {
  path: string           // URL path visited
  title?: string         // Page title
  referrer?: string      // HTTP referrer
  userAgent?: string     // Browser user agent
  ipAddress?: string     // Visitor IP address
  sessionId?: string     // Unique session ID
  userId?: number        // User ID (if authenticated)
  duration?: number      // Time on page (milliseconds)
}

Manual Page View Tracking

Track page views programmatically:

Track Page View

import { analyticsService } from '@sonicjs-cms/core/plugins'

// Track a page view
const result = await analyticsService.trackPageView({
  path: '/products/item-123',
  title: 'Product Detail - Widget Pro',
  sessionId: 'session-xyz',
  userId: 456
})

console.log('View tracked:', result.viewId)

Custom Events

Track custom events to measure user interactions and conversions.

Event Structure

Event Data

interface AnalyticsEvent {
  eventType: string      // Category: 'auth', 'content', 'conversion', etc.
  eventName: string      // Specific event: 'user_login', 'purchase', etc.
  eventData?: object     // Additional metadata
  path?: string          // Page where event occurred
  sessionId?: string     // Associated session
  userId?: number        // Associated user
}

Track Custom Events

Track Events

import { analyticsService } from '@sonicjs-cms/core/plugins'

// Track a conversion event
await analyticsService.trackEvent({
  eventType: 'conversion',
  eventName: 'purchase_completed',
  eventData: {
    orderId: 'order-12345',
    amount: 99.99,
    currency: 'USD',
    items: 3
  },
  sessionId: 'session-xyz',
  userId: 456
})

// Track a feature usage event
await analyticsService.trackEvent({
  eventType: 'feature',
  eventName: 'export_clicked',
  eventData: {
    format: 'csv',
    recordCount: 150
  }
})

// Track a content event
await analyticsService.trackEvent({
  eventType: 'content',
  eventName: 'article_shared',
  eventData: {
    articleId: 'post-789',
    platform: 'twitter'
  },
  path: '/blog/my-article'
})

Common Event Types

Event TypeUse Case
authLogin, logout, registration
contentViews, shares, downloads
conversionPurchases, sign-ups, goals
featureFeature usage, button clicks
errorClient-side errors, failures
customAny other events

API Reference

All analytics endpoints require authentication with admin or analytics:read role.

Get Statistics

Retrieve analytics overview statistics for a time range.

Query Parameters:

  • range - Time range: 1d, 7d, 30d, 90d (default: 7d)
  • metric - Specific metric: pageviews, sessions, users, all (default: all)

Request

curl -X GET 'https://your-app.workers.dev/api/analytics/stats?range=7d' \
  -H 'Authorization: Bearer YOUR_TOKEN'

Response

{
  "message": "Analytics stats",
  "data": {
    "pageviews": 12500,
    "uniqueVisitors": 3200,
    "sessions": 4800,
    "avgSessionDuration": 245,
    "bounceRate": 0.35,
    "topPages": [
      { "path": "/", "views": 3200 },
      { "path": "/about", "views": 1800 },
      { "path": "/contact", "views": 950 }
    ],
    "timeRange": "7d"
  }
}

Track Event

Track a custom analytics event.

Request Body:

  • eventType (required) - Event category
  • eventName (required) - Specific event name
  • eventData - Optional metadata object
  • path - Page path
  • sessionId - Session identifier
  • userId - User ID

Request

curl -X POST 'https://your-app.workers.dev/api/analytics/track' \
  -H 'Authorization: Bearer YOUR_TOKEN' \
  -H 'Content-Type: application/json' \
  -d '{
    "eventType": "conversion",
    "eventName": "signup_completed",
    "eventData": { "plan": "pro" }
  }'

Response

{
  "message": "Event tracked successfully",
  "eventId": "event-1234567890"
}

Generate Report

Generate detailed analytics reports.

Query Parameters:

  • type - Report type: traffic, pages, users, behavior (default: traffic)
  • start - Start date (ISO format)
  • end - End date (ISO format)

Request

curl -X GET 'https://your-app.workers.dev/api/analytics/reports?type=traffic&start=2024-01-01&end=2024-01-31' \
  -H 'Authorization: Bearer YOUR_TOKEN'

Response

{
  "message": "Analytics report",
  "data": {
    "reportType": "traffic",
    "dateRange": {
      "start": "2024-01-01",
      "end": "2024-01-31"
    },
    "data": []
  }
}

Real-time Data

Get real-time analytics showing active users and pages.

Request

curl -X GET 'https://your-app.workers.dev/api/analytics/realtime' \
  -H 'Authorization: Bearer YOUR_TOKEN'

Response

{
  "message": "Real-time analytics",
  "data": {
    "activeUsers": 23,
    "activePages": [
      { "path": "/", "users": 8 },
      { "path": "/blog", "users": 5 },
      { "path": "/products", "users": 4 }
    ],
    "recentEvents": []
  }
}

Analytics Service

Use the analytics service programmatically in your code.

Access the Service

Service Access

// In hooks or middleware with context
const analyticsService = context.services?.analyticsService

// Track page view
const view = await analyticsService?.trackPageView({
  path: '/my-page',
  title: 'My Page'
})

// Track event
const event = await analyticsService?.trackEvent({
  eventType: 'custom',
  eventName: 'button_clicked'
})

// Get statistics
const stats = await analyticsService?.getStats('7d')
console.log(`${stats.pageviews} views this week`)

// Generate report
const report = await analyticsService?.generateReport('traffic', {
  start: '2024-01-01',
  end: '2024-01-31'
})

Service Methods

MethodParametersReturns
trackPageView(data)PageView object{ viewId: string }
trackEvent(event)AnalyticsEvent object{ eventId: string }
getStats(range)'1d', '7d', '30d', '90d'Statistics object
generateReport(type, options)Report type and date range{ reportId: string }

Admin Dashboard

The plugin provides admin pages for viewing analytics.

Dashboard

Path: /admin/analytics

Overview of key metrics:

  • Total page views
  • Unique visitors
  • Session count
  • Top pages

Reports

Path: /admin/analytics/reports

Generate custom reports:

  • Select report type
  • Choose date range
  • Export data

Real-time

Path: /admin/analytics/realtime

Live monitoring:

  • Active user count
  • Active pages with visitor counts
  • Recent events feed

Settings

Path: /admin/analytics/settings

Configure the plugin:

  • Enable/disable tracking
  • Data retention settings
  • Feature toggles

Configuration

Plugin Settings

SettingTypeDefaultDescription
trackPageViewsbooleantrueAutomatically track page views
trackUserSessionsbooleantrueTrack session duration and behavior
retentionDaysnumber90Days to retain analytics data

Permissions

PermissionDescription
analytics:viewView analytics data
analytics:readRead access to analytics API
analytics:exportExport analytics reports
analytics:configureChange plugin settings

Hooks Integration

The plugin integrates with these hooks:

HookPriorityPurpose
REQUEST_START1Initialize session tracking
REQUEST_END1Finalize request metrics
USER_LOGIN8Track login events
content:view8Track content views

Hook Example

// The plugin automatically tracks logins
// You can also manually track with hooks

hooks.register('content:view', async (data, context) => {
  const analyticsService = context.services?.analyticsService

  await analyticsService?.trackEvent({
    eventType: 'content',
    eventName: 'content_viewed',
    eventData: {
      contentId: data.id,
      contentType: data.type,
      title: data.title
    }
  })

  return data
})

Database Schema

analytics_pageviews

ColumnTypeDescription
idINTEGERPrimary key
pathTEXTPage path visited
titleTEXTPage title
referrerTEXTHTTP referrer
user_agentTEXTBrowser user agent
ip_addressTEXTVisitor IP
session_idTEXTSession identifier
user_idINTEGERUser ID if authenticated
durationINTEGERTime on page (ms)
created_atINTEGERTimestamp

analytics_events

ColumnTypeDescription
idINTEGERPrimary key
event_typeTEXTEvent category
event_nameTEXTEvent name
event_dataTEXTJSON metadata
pathTEXTPage path
session_idTEXTSession identifier
user_idINTEGERUser ID
created_atINTEGERTimestamp

Next Steps

Was this page helpful?