Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions content/Frontend/react-hooks.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
</Callout>

## 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 (
<button onClick={trackClick('add_to_cart', { productId })}>
Add to Cart
</button>
);
}
```

## 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
2 changes: 1 addition & 1 deletion content/Services/Observability/meta.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"title": "Observability",
"pages": ["logging", "tracing", "sessions-debugging"]
"pages": ["logging", "tracing", "sessions-debugging", "web-analytics"]
}
220 changes: 220 additions & 0 deletions content/Services/Observability/web-analytics.mdx
Original file line number Diff line number Diff line change
@@ -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 |
Comment on lines +50 to +61
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for AnalyticsConfig interface definition

echo "=== Searching for AnalyticsConfig interface ==="
find . -type f \( -name "*.ts" -o -name "*.tsx" -o -name "*.js" -o -name "*.jsx" \) ! -path "*/node_modules/*" ! -path "*/.next/*" ! -path "*/dist/*" -exec grep -l "AnalyticsConfig" {} \;

echo ""
echo "=== Searching with ast-grep for interface definition ==="
ast-grep --pattern 'interface AnalyticsConfig { $$$ }' 2>/dev/null || true

echo ""
echo "=== Searching with rg for AnalyticsConfig ==="
rg -n -B2 -A 20 'interface AnalyticsConfig|type AnalyticsConfig' --type ts --type tsx 2>/dev/null | head -100

echo ""
echo "=== Listing repository structure to understand codebase ==="
git ls-files | grep -E '(analytics|sdk|config)' | head -30

Repository: agentuity/docs

Length of output: 2098


Add missing configuration options and fix type precision.

The documentation table is incomplete. The AnalyticsConfig interface includes two additional options not listed: trackOutboundLinks (boolean, default true) and trackForms (boolean, default true). Additionally, the globalProperties type should be Record<string, unknown> rather than generic object for clarity.

Complete configuration table
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
trackOutboundLinks boolean true Track outbound link clicks
trackForms boolean true Track form submissions
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 Record<string, unknown> {} Properties added to all events
🤖 Prompt for AI Agents
In `@content/Services/Observability/web-analytics.mdx` around lines 50 - 61,
Update the web-analytics docs table to match the AnalyticsConfig interface by
adding the missing boolean options trackOutboundLinks (default true) and
trackForms (default true), and change the type of globalProperties from generic
object to Record<string, unknown>; ensure the table row names match the existing
option names (e.g., trackClicks, trackScroll, trackWebVitals, trackErrors,
trackSPANavigation, sampleRate, excludePatterns) so the doc and the
AnalyticsConfig symbol stay in sync.


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
<button data-analytics="signup-button">Sign Up</button>
<a href="/pricing" data-analytics="pricing-link">View Pricing</a>
```

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 (
<div>
<button onClick={trackClick('add_to_cart', { productId })}>
Add to Cart
</button>
<button onClick={handlePurchase}>Buy Now</button>
</div>
);
}
```

| 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 <div>Product {productId}</div>;
}
```

| 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 <div>Welcome!</div>;
}

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