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:
| Table | Purpose |
|---|---|
analytics_pageviews | Stores page view records |
analytics_events | Stores 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 Type | Use Case |
|---|---|
auth | Login, logout, registration |
content | Views, shares, downloads |
conversion | Purchases, sign-ups, goals |
feature | Feature usage, button clicks |
error | Client-side errors, failures |
custom | Any 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 categoryeventName(required) - Specific event nameeventData- Optional metadata objectpath- Page pathsessionId- Session identifieruserId- 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
| Method | Parameters | Returns |
|---|---|---|
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
| Setting | Type | Default | Description |
|---|---|---|---|
trackPageViews | boolean | true | Automatically track page views |
trackUserSessions | boolean | true | Track session duration and behavior |
retentionDays | number | 90 | Days to retain analytics data |
Permissions
| Permission | Description |
|---|---|
analytics:view | View analytics data |
analytics:read | Read access to analytics API |
analytics:export | Export analytics reports |
analytics:configure | Change plugin settings |
Hooks Integration
The plugin integrates with these hooks:
| Hook | Priority | Purpose |
|---|---|---|
REQUEST_START | 1 | Initialize session tracking |
REQUEST_END | 1 | Finalize request metrics |
USER_LOGIN | 8 | Track login events |
content:view | 8 | Track 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
| Column | Type | Description |
|---|---|---|
id | INTEGER | Primary key |
path | TEXT | Page path visited |
title | TEXT | Page title |
referrer | TEXT | HTTP referrer |
user_agent | TEXT | Browser user agent |
ip_address | TEXT | Visitor IP |
session_id | TEXT | Session identifier |
user_id | INTEGER | User ID if authenticated |
duration | INTEGER | Time on page (ms) |
created_at | INTEGER | Timestamp |
analytics_events
| Column | Type | Description |
|---|---|---|
id | INTEGER | Primary key |
event_type | TEXT | Event category |
event_name | TEXT | Event name |
event_data | TEXT | JSON metadata |
path | TEXT | Page path |
session_id | TEXT | Session identifier |
user_id | INTEGER | User ID |
created_at | INTEGER | Timestamp |