Web Analytics — Agentuity Documentation

Web Analytics

Track page views, user engagement, and custom events in your frontend

Understand how users experience your frontend without adding instrumentation code. Page views, scroll depth, Web Vitals, and custom events are collected automatically.

What Gets Tracked

The beacon automatically collects the following on every page view:

CategoryData
Page contextURL, path, referrer, title (query strings stripped for privacy)
DeviceScreen dimensions, viewport size, pixel ratio, user agent, language
GeolocationCountry, region, city, timezone, coordinates (IP-based)
PerformanceLoad time, DOM ready, TTFB
Web VitalsFCP, LCP, CLS, INP
EngagementScroll depth, time on page, attention sessions
UTM paramsutm_source, utm_medium, utm_campaign, utm_term, utm_content
SPA navigationVirtual page views on pushState/replaceState
ErrorsJavaScript errors and unhandled promise rejections

Events are batched and sent when the user navigates away (on visibilitychange or pagehide), with a sessionStorage fallback to recover data if unload events don't fire.

Configuration

Analytics are enabled by default. Customize tracking behavior in your agentuity.json:

{
  "analytics": {
    "enabled": true,
    "trackClicks": true,
    "trackScroll": true,
    "trackWebVitals": true,
    "trackErrors": true,
    "trackSPANavigation": true,
    "sampleRate": 1
  }
}
OptionTypeDefaultDescription
enabledbooleantrueEnable or disable analytics
trackClicksbooleantrueTrack clicks on elements with data-analytics attribute
trackScrollbooleantrueTrack scroll depth milestones (25%, 50%, 75%, 100%)
trackWebVitalsbooleantrueTrack Core Web Vitals (FCP, LCP, CLS, INP)
trackErrorsbooleantrueTrack JavaScript errors and unhandled rejections
trackSPANavigationbooleantrueTrack client-side route changes via pushState/replaceState
sampleRatenumber1Sample rate from 0 to 1 (1 = track 100% of page views)
excludePatternsstring[][]URL patterns (regex) to exclude from tracking

To disable analytics entirely:

{
  "analytics": false
}

Custom Event Tracking

Data Attributes

Add data-analytics to any element to track clicks without writing JavaScript:

<button data-analytics="signup_button">Sign Up</button>
<a href="/pricing" data-analytics="pricing_link">View Pricing</a>

JavaScript API

Track events programmatically using the @agentuity/frontend package:

import { track, getAnalytics } from '@agentuity/frontend';
 
// Track a custom event
track('purchase_completed', {
  productId: 'prod_123',
  amount: 99.99,
  currency: 'USD',
});
 
// Access the full analytics client for identify and flush
const analytics = getAnalytics();
analytics?.identify('user_456', { plan: 'pro' });
analytics?.flush();

The same client is also available globally as window.agentuityAnalytics for non-module contexts (inline scripts, third-party integrations):

window.agentuityAnalytics?.track('cta_clicked', { location: 'hero' });

React Integration

The @agentuity/react package provides hooks for type-safe analytics in React components.

useAnalytics

import { useAnalytics } from '@agentuity/react';
 
function ProductPage({ productId }: { productId: string }) {
  const { track, trackClick, identify, ready } = useAnalytics();
 
  const handlePurchase = () => {
    track('purchase_started', { productId });
  };
 
  return (
    <div>
      <button onClick={trackClick('add_to_cart', { productId })}>
        Add to Cart
      </button>
      <button onClick={handlePurchase}>Buy Now</button>
    </div>
  );
}
PropertyTypeDescription
track(eventName, properties?) => voidTrack a custom event
trackClick(eventName, properties?) => (event) => voidReturns a click handler that tracks an event
identify(userId, traits?) => voidIdentify the current user
flush() => voidForce-send pending events
readybooleantrue when the analytics client is available

useTrackOnMount

Track an event when a component mounts:

import { useTrackOnMount } from '@agentuity/react';
 
function ProductPage({ productId }: { productId: string }) {
  // Fires once per component instance by default
  useTrackOnMount({
    eventName: 'product_viewed',
    properties: { productId },
  });
 
  return <div>Product {productId}</div>;
}
OptionTypeDefaultDescription
eventNamestring-Event name to track
propertiesobject-Event properties
oncebooleantrueOnly track once per component instance

withPageTracking

Higher-order component that tracks a page_view event on mount:

import { withPageTracking } from '@agentuity/react';
 
function HomePage() {
  return <div>Welcome!</div>;
}
 
export default withPageTracking(HomePage, 'home');

Privacy and Opt-Out

The analytics beacon collects data with privacy in mind:

  • No cookies for tracking: Visitor IDs use localStorage and can be cleared by the user
  • Query strings stripped: URLs are sanitized before sending to prevent leaking tokens or PII
  • Sampling: Use sampleRate to reduce data collection on high-traffic pages

Users can opt out of tracking programmatically:

import { setOptOut, isOptedOut } from '@agentuity/frontend';
 
// Let users control their tracking preference
function PrivacyToggle() {
  const optedOut = isOptedOut();
 
  return (
    <button onClick={() => setOptOut(!optedOut)}>
      {optedOut ? 'Enable Analytics' : 'Disable Analytics'}
    </button>
  );
}

Next Steps

  • React Hooks: useAnalytics and other hooks for React integration
  • Logging: Structured logging for agents and routes
  • Tracing: OpenTelemetry spans for performance debugging