Analytics Plugin
Analytics tracking and reporting
Analytics Plugin
The Analytics Plugin provides comprehensive analytics tracking and reporting with real-time metrics, custom events, funnels, and user behavior analysis.
Installation
npm install @deessejs/plugin-analyticsConfiguration
// deesse.config.ts
import { defineConfig } from '@deessejs/core'
import { analyticsPlugin } from '@deessejs/plugin-analytics'
export const config = defineConfig({
plugins: [
analyticsPlugin({
// Privacy & GDPR
privacy: {
anonymizeIp: true, // Anonymize IP addresses
respectDNT: true, // Respect Do Not Track
cookieConsent: true, // Require consent
retentionDays: 90, // Data retention period
},
// Sampling
sampling: {
enabled: false, // Disable for accuracy
rate: 100, // 100% of traffic
},
// Session tracking
session: {
timeout: 30, // Session timeout in minutes
autoTrack: true, // Auto-track page views
trackScroll: true, // Track scroll depth
trackClicks: true, // Track outbound clicks
trackMedia: true, // Track video/audio engagement
},
// E-commerce tracking
ecommerce: {
enabled: true,
trackCart: true,
trackPurchases: true,
trackRevenue: true,
},
// Custom dimensions
customDimensions: {
userType: ['guest', 'registered', 'premium'],
contentCategory: ['blog', 'tutorial', 'documentation'],
},
// Integrations
integrations: {
googleAnalytics: {
enabled: true,
measurementId: process.env.GA_MEASUREMENT_ID,
},
plausible: {
enabled: true,
domain: 'yourdomain.com',
},
umami: {
enabled: true,
websiteId: process.env.UMAMI_WEBSITE_ID,
},
},
// Data pipeline
pipeline: {
queue: true, // Queue events for processing
batchSize: 100, // Batch size for sending
flushInterval: 5000, // Flush every 5 seconds
},
}),
],
})Collections
Events
Analytics event tracking:
{
name: 'analyticsEvents',
fields: [
{
name: 'sessionId',
type: 'string',
required: true,
},
{
name: 'eventType',
type: 'enum',
enum: [
'pageview',
'event',
'scroll',
'click',
'form_submit',
'purchase',
'custom'
],
required: true,
},
{
name: 'eventName',
type: 'string',
},
{
name: 'url',
type: 'string',
},
{
name: 'path',
type: 'string',
},
{
name: 'referrer',
type: 'string',
},
{
name: 'userAgent',
type: 'string',
},
{
name: 'ip',
type: 'string',
},
{
name: 'properties',
type: 'json',
admin: {
description: 'Event properties',
},
},
{
name: 'userId',
type: 'string',
},
{
name: 'anonymousId',
type: 'string',
},
{
name: 'timestamp',
type: 'datetime',
defaultValue: () => new Date(),
},
],
}Sessions
User session tracking:
{
name: 'analyticsSessions',
fields: [
{
name: 'sessionId',
type: 'string',
unique: true,
required: true,
},
{
name: 'userId',
type: 'string',
},
{
name: 'anonymousId',
type: 'string',
},
{
name: 'startTime',
type: 'datetime',
defaultValue: () => new Date(),
},
{
name: 'endTime',
type: 'datetime',
},
{
name: 'duration',
type: 'number',
admin: {
readOnly: true,
},
},
{
name: 'pageViews',
type: 'number',
defaultValue: 0,
},
{
name: 'events',
type: 'number',
defaultValue: 0,
},
{
name: 'entryPage',
type: 'string',
},
{
name: 'exitPage',
type: 'string',
},
{
name: 'referrer',
type: 'string',
},
{
name: 'utmSource',
type: 'string',
},
{
name: 'utmMedium',
type: 'string',
},
{
name: 'utmCampaign',
type: 'string',
},
{
name: 'device',
type: 'string',
},
{
name: 'browser',
type: 'string',
},
{
name: 'os',
type: 'string',
},
{
name: 'country',
type: 'string',
},
{
name: 'city',
type: 'string',
},
],
}Funnels
Conversion funnel tracking:
{
name: 'analyticsFunnels',
fields: [
{
name: 'name',
type: 'string',
required: true,
},
{
name: 'description',
type: 'text',
},
{
name: 'steps',
type: 'array',
required: true,
admin: {
description: 'Funnel steps in order',
},
},
{
name: 'goal',
type: 'string',
required: true,
admin: {
description: 'Final goal event',
},
},
{
name: 'window',
type: 'number',
defaultValue: 7,
admin: {
description: 'Time window in days',
},
},
],
}Reports
Saved analytics reports:
{
name: 'analyticsReports',
fields: [
{
name: 'name',
type: 'string',
required: true,
},
{
name: 'type',
type: 'enum',
enum: ['overview', 'traffic', 'content', 'ecommerce', 'custom'],
required: true,
},
{
name: 'config',
type: 'json',
required: true,
admin: {
description: 'Report configuration',
},
},
{
name: 'schedule',
type: 'enum',
enum: ['daily', 'weekly', 'monthly', 'none'],
defaultValue: 'none',
},
{
name: 'recipients',
type: 'array',
admin: {
description: 'Email report to',
},
},
],
}Client-Side Tracking
Automatic Page Views
// Automatically tracks page views
// Just include the provider in your layout
import { AnalyticsProvider } from '@deessejs/plugin-analytics/client'
export default function RootLayout({ children }) {
return (
<html>
<body>
<AnalyticsProvider>{children}</AnalyticsProvider>
</body>
</html>
)
}Custom Events
'use client'
import { trackEvent } from '@deessejs/plugin-analytics/client'
export function SignupButton() {
const handleSignup = () => {
// Track signup event
trackEvent('signup_clicked', {
buttonLocation: 'header',
plan: 'premium',
})
}
return <button onClick={handleSignup}>Sign Up</button>
}E-commerce Events
'use client'
import {
trackProductView,
trackAddToCart,
trackPurchase,
} from '@deessejs/plugin-analytics/client'
export function ProductPage({ product }) {
useEffect(() => {
trackProductView({
productId: product.id,
name: product.name,
price: product.price,
category: product.category,
})
}, [product])
const addToCart = () => {
trackAddToCart({
productId: product.id,
name: product.name,
price: product.price,
quantity: 1,
})
}
return (
<div>
<h1>{product.name}</h1>
<button onClick={addToCart}>Add to Cart</button>
</div>
)
}
// Checkout complete
trackPurchase({
orderId: 'ORD-123',
revenue: 99.99,
tax: 10.00,
shipping: 5.00,
currency: 'USD',
products: [
{ productId: '1', name: 'Product 1', price: 49.99, quantity: 2 },
],
})Form Tracking
'use client'
import { trackFormSubmit } from '@deessejs/plugin-analytics/client'
export function ContactForm() {
const handleSubmit = (data: FormData) => {
// Track form submission
trackFormSubmit('contact_form', {
formType: 'contact',
hasMessage: !!data.get('message'),
})
}
return (
<form action={handleSubmit}>
{/* Form fields */}
</form>
)
}Server-Side Tracking
Page View Tracking
import { trackPageView } from '@deessejs/plugin-analytics/server'
export default async function Page() {
// Track server-side page view
await trackPageView({
path: '/blog/post-1',
title: 'Blog Post',
})
return <div>Page content</div>
}Custom Server Events
import { trackEvent } from '@deessejs/plugin-analytics/server'
export async function POST(request: Request) {
const data = await request.json()
// Track custom event
await trackEvent('api_call', {
endpoint: '/api/checkout',
method: 'POST',
success: true,
})
return Response.json({ success: true })
}Admin Dashboard Components
AnalyticsOverview Component
import { AnalyticsOverview } from '@deessejs/plugin-analytics/admin'
export default function DashboardPage() {
return (
<AnalyticsOverview
period="7d" // '24h', '7d', '30d', '90d', 'custom'
showVisitors
showPageViews
showSessions
showBounceRate
showAvgSession
/>
)
}TrafficSources Component
import { TrafficSources } from '@deessejs/plugin-analytics/admin'
export default function SourcesPage() {
return (
<TrafficSources
period="30d"
groupBy="source" // 'source', 'medium', 'campaign'
showChart
showTable
/>
)
}ContentPerformance Component
import { ContentPerformance } from '@deessejs/plugin-analytics/admin'
export default function ContentPage() {
return (
<ContentPerformance
period="30d"
sortBy="pageViews" // 'pageViews', 'uniqueVisitors', 'avgTime'
limit={50}
showTrend
/>
)
}RealTime Component
import { RealTime } from '@deessejs/plugin-analytics/admin'
export default function LivePage() {
return (
<RealTime
showCurrentVisitors
showTopPages
showTopSources
refreshInterval={5} // Seconds
/>
)
}FunnelAnalysis Component
import { Funnels } from '@deessejs/plugin-analytics/admin'
export default function FunnelsPage() {
return (
<Funnels
funnelId="checkout"
period="30d"
showConversionRate
showDropOff
showTimeToConvert
/>
)
}API Routes
# Track events
POST /api/analytics/track
# Get analytics data
GET /api/analytics/overview
GET /api/analytics/traffic
GET /api/analytics/content
GET /api/analytics/events
# Real-time data
GET /api/analytics/realtime
# Funnels
GET /api/analytics/funnels
GET /api/analytics/funnels/:id
# Reports
GET /api/analytics/reports
POST /api/analytics/reports
GET /api/analytics/reports/:id
# Export
GET /api/analytics/export/csv
GET /api/analytics/export/jsonCustom Reports
import { createReport } from '@deessejs/plugin-analytics/server'
// Create custom report
const report = await createReport({
name: 'Blog Performance',
type: 'content',
config: {
metrics: ['pageViews', 'uniqueVisitors', 'avgTimeOnPage'],
filters: {
path: { startsWith: '/blog' },
dateRange: { from: '2025-01-01', to: '2025-01-31' },
},
groupBy: ['path'],
sortBy: 'pageViews',
limit: 20,
},
})Data Privacy
analyticsPlugin({
privacy: {
// Anonymize IPs before storing
anonymizeIp: true,
// Respect Do Not Track header
respectDNT: true,
// Require cookie consent
cookieConsent: {
enabled: true,
consentManager: 'custom', // 'custom', 'cookiebot', 'onetrust'
},
// Data retention
retentionDays: 90,
retentionJob: 'daily',
// Right to deletion
allowDeletion: true,
deletionRequestEndpoint: '/api/analytics/gdpr/delete',
},
})Performance Optimization
analyticsPlugin({
performance: {
// Sampling to reduce load
sampling: {
enabled: false, // Disable for accuracy
rate: 100,
},
// Batching events
batching: {
enabled: true,
batchSize: 100,
flushInterval: 5000,
},
// Queue for processing
queue: {
enabled: true,
provider: 'redis', // 'memory', 'redis', 'bullmq'
},
// Caching
cache: {
enabled: true,
ttl: 300, // 5 minutes
},
},
})Integration Examples
Google Analytics 4
analyticsPlugin({
integrations: {
googleAnalytics: {
enabled: true,
measurementId: 'G-XXXXXXXXXX',
sendPageView: true,
debugMode: process.env.NODE_ENV === 'development',
},
},
})Plausible Analytics
analyticsPlugin({
integrations: {
plausible: {
enabled: true,
domain: 'yourdomain.com',
scriptUrl: 'https://plausible.io/js/script.js',
},
},
})Umami
analyticsPlugin({
integrations: {
umami: {
enabled: true,
websiteId: process.env.UMAMI_WEBSITE_ID,
hostUrl: 'https://analytics.umami.is',
},
},
})Next Steps
- Explore the Blog Plugin
- Learn about Students Plugin
- Return to Plugins Overview