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 ( +