From da89c0a86213a022c31916f8942f7282e4e40def Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sun, 1 Feb 2026 16:23:36 +0000 Subject: [PATCH] Add web analytics documentation - Create web-analytics.mdx in Services/Observability covering: - Automatic page view tracking features - Configuration options - Custom event tracking (data attributes and JS API) - React integration (useAnalytics, useTrackOnMount, withPageTracking) - Privacy considerations - Update Observability meta.json to include web-analytics - Add Analytics Hooks section to Frontend/react-hooks.mdx with link to main docs Co-Authored-By: Rick Blalock --- content/Frontend/react-hooks.mdx | 25 ++ content/Services/Observability/meta.json | 2 +- .../Services/Observability/web-analytics.mdx | 220 ++++++++++++++++++ 3 files changed, 246 insertions(+), 1 deletion(-) create mode 100644 content/Services/Observability/web-analytics.mdx diff --git a/content/Frontend/react-hooks.mdx b/content/Frontend/react-hooks.mdx index 04988dc9..c0f2c824 100644 --- a/content/Frontend/react-hooks.mdx +++ b/content/Frontend/react-hooks.mdx @@ -316,8 +316,33 @@ function ProtectedContent() { `useAuth` provides auth-specific state. For non-auth context like `baseUrl`, use `useAgentuity()` instead. See [Authentication](/Frontend/authentication) for integrating with identity providers. +## Analytics Hooks + +Track user behavior and custom events with analytics hooks. See [Web Analytics](/Services/Observability/web-analytics) for full documentation. + +```tsx +import { useAnalytics, useTrackOnMount } from '@agentuity/react'; + +function ProductPage({ productId }: { productId: string }) { + const { track, trackClick } = useAnalytics(); + + // Track page view on mount + useTrackOnMount({ + eventName: 'product_viewed', + properties: { productId }, + }); + + return ( + + ); +} +``` + ## Next Steps - [Provider Setup](/Frontend/provider-setup): Configure `AgentuityProvider` for deployments - [Advanced Hooks](/Frontend/advanced-hooks): Custom handlers for WebSocket and SSE - [Deployment Scenarios](/Frontend/deployment-scenarios): Choose where your frontend lives +- [Web Analytics](/Services/Observability/web-analytics): Track page views and custom events diff --git a/content/Services/Observability/meta.json b/content/Services/Observability/meta.json index 8cb23a5a..de9e18f4 100644 --- a/content/Services/Observability/meta.json +++ b/content/Services/Observability/meta.json @@ -1,4 +1,4 @@ { "title": "Observability", - "pages": ["logging", "tracing", "sessions-debugging"] + "pages": ["logging", "tracing", "sessions-debugging", "web-analytics"] } diff --git a/content/Services/Observability/web-analytics.mdx b/content/Services/Observability/web-analytics.mdx new file mode 100644 index 00000000..7ff72f31 --- /dev/null +++ b/content/Services/Observability/web-analytics.mdx @@ -0,0 +1,220 @@ +--- +title: Web Analytics +description: Track page views, user engagement, and custom events in your frontend +--- + +Agentuity automatically tracks page views, user engagement, and performance metrics in your frontend applications. Analytics are enabled by default and require no additional setup. + +## What's Tracked Automatically + +When analytics are enabled, the SDK automatically collects: + +**Page Context** includes the URL, path, referrer, and page title for each page view. Query strings are stripped from URLs to prevent sensitive data leakage. + +**Device Information** captures screen dimensions, viewport size, device pixel ratio, user agent, and browser language. + +**Geo Location** provides country, region, city, timezone, and coordinates based on the visitor's IP address. + +**Performance Metrics** measure load time, DOM ready time, and Time to First Byte (TTFB). + +**Web Vitals** track First Contentful Paint (FCP), Largest Contentful Paint (LCP), Cumulative Layout Shift (CLS), and Interaction to Next Paint (INP). + +**Engagement** records scroll depth (with milestones at 25%, 50%, 75%, 100%), time on page, and attention sessions when users return to the page. + +**UTM Parameters** are captured from the URL query string (utm_source, utm_medium, utm_campaign, utm_term, utm_content). + +**SPA Navigation** is tracked automatically when using history.pushState or history.replaceState, sending a page view for each navigation. + +**Errors** are captured including JavaScript errors and unhandled promise rejections. + +## Configuration + +Configure analytics in your `agentuity.json` file: + +```json +{ + "analytics": { + "enabled": true, + "trackClicks": true, + "trackScroll": true, + "trackWebVitals": true, + "trackErrors": true, + "trackSPANavigation": true, + "sampleRate": 1, + "excludePatterns": [], + "globalProperties": {} + } +} +``` + +| Option | Type | Default | Description | +|--------|------|---------|-------------| +| `enabled` | `boolean` | `true` | Enable or disable analytics | +| `requireConsent` | `boolean` | `false` | Require user consent before tracking | +| `trackClicks` | `boolean` | `true` | Track clicks on elements with `data-analytics` attribute | +| `trackScroll` | `boolean` | `true` | Track scroll depth milestones | +| `trackWebVitals` | `boolean` | `true` | Track Core Web Vitals metrics | +| `trackErrors` | `boolean` | `true` | Track JavaScript errors | +| `trackSPANavigation` | `boolean` | `true` | Track SPA route changes | +| `sampleRate` | `number` | `1` | Sample rate from 0 to 1 (1 = 100% of page views) | +| `excludePatterns` | `string[]` | `[]` | URL patterns to exclude from tracking | +| `globalProperties` | `object` | `{}` | Properties added to all events | + +To disable analytics entirely: + +```json +{ + "analytics": false +} +``` + +## Custom Event Tracking + +### Using Data Attributes + +Add the `data-analytics` attribute to any element to track clicks: + +```html + +View Pricing +``` + +Clicks on these elements are automatically tracked with the event name `click:{attribute-value}`. + +### Using the JavaScript API + +Track custom events programmatically using the global `window.agentuityAnalytics` object: + +```typescript +// Track a custom event +window.agentuityAnalytics.track('purchase_completed', { + productId: 'prod_123', + amount: 99.99, + currency: 'USD', +}); + +// Identify the current user +window.agentuityAnalytics.identify('user_456', { + email: 'user@example.com', + plan: 'pro', +}); + +// Force send pending data immediately +window.agentuityAnalytics.flush(); +``` + +Events are batched and sent when the user leaves the page (on `visibilitychange` or `pagehide` events) to minimize network requests. + +## React Integration + +The `@agentuity/react` package provides hooks for tracking analytics in React components. + +### useAnalytics Hook + +```tsx +import { useAnalytics } from '@agentuity/react'; + +function ProductPage({ productId }: { productId: string }) { + const { track, trackClick, identify, ready } = useAnalytics(); + + const handlePurchase = () => { + track('purchase_started', { productId }); + // ... purchase logic + }; + + return ( +
+ + +
+ ); +} +``` + +| Property | Type | Description | +|----------|------|-------------| +| `track` | `(eventName, properties?) => void` | Track a custom event | +| `trackClick` | `(eventName, properties?) => (event) => void` | Get a click handler that tracks an event | +| `identify` | `(userId, traits?) => void` | Identify the current user | +| `flush` | `() => void` | Flush pending events | +| `ready` | `boolean` | Whether the analytics client is available | + +### useTrackOnMount Hook + +Track an event when a component mounts: + +```tsx +import { useTrackOnMount } from '@agentuity/react'; + +function ProductPage({ productId }: { productId: string }) { + useTrackOnMount({ + eventName: 'product_viewed', + properties: { productId }, + }); + + return
Product {productId}
; +} +``` + +| Option | Type | Default | Description | +|--------|------|---------|-------------| +| `eventName` | `string` | - | Event name to track | +| `properties` | `object` | - | Event properties | +| `once` | `boolean` | `true` | Only track once per component instance | + +### withPageTracking HOC + +Wrap a component to automatically track page views: + +```tsx +import { withPageTracking } from '@agentuity/react'; + +function HomePage() { + return
Welcome!
; +} + +export default withPageTracking(HomePage, 'home'); +``` + +## Privacy Considerations + +The analytics beacon is designed with privacy in mind: + +**Query strings are stripped** from URLs before sending to prevent accidental capture of sensitive data like tokens or personal information. + +**No cookies for tracking** - visitor IDs are stored in localStorage and can be cleared by the user. + +**Opt-out support** - users can opt out of tracking: + +```typescript +import { setOptOut, isOptedOut } from '@agentuity/frontend'; + +// Check if user has opted out +if (isOptedOut()) { + console.log('User has opted out of analytics'); +} + +// Set opt-out preference +setOptOut(true); // Opt out +setOptOut(false); // Opt back in +``` + +**Dev mode logging** - in development, analytics data is logged to the console instead of being sent to the server, making it easy to debug without polluting production data. + +## Viewing Analytics Data + +Analytics data is available in the Agentuity Cloud console. You can view page views, user engagement metrics, and custom events for your project. + +Use the CLI to check your project's analytics configuration: + +```bash +agentuity cloud project info +``` + +## Next Steps + +- [Logging](/Services/Observability/logging): Add structured logging to your agents and routes +- [Tracing](/Services/Observability/tracing): Track timing and debug performance with OpenTelemetry spans +- [React Hooks](/Frontend/react-hooks): Learn about other React hooks for API calls and real-time communication