or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

custom-events.mdindex.mdoutbound-link.mdplugin-configuration.md
tile.json

custom-events.mddocs/

Custom Event Tracking

Global gtag function for firing custom events and conversions with Google tracking services.

Capabilities

Global Gtag Function

The plugin makes the global gtag function available for custom event tracking across all configured Google services.

/**
 * Global gtag function for custom event tracking and configuration
 * Available on window object after plugin initialization
 * @param command - The gtag command ("event", "config", "js")
 * @param eventNameOrTrackingIdOrDate - Event name, tracking ID, or Date object depending on command
 * @param parameters - Optional event parameters and configuration
 */
declare function gtag(
  command: "event" | "config" | "js",
  eventNameOrTrackingIdOrDate: string | Date,
  parameters?: EventParameters | GtagConfig
): void;

interface EventParameters {
  /** Category for grouping events (e.g., "engagement", "conversion") */
  event_category?: string;
  /** Human-readable label for the event */
  event_label?: string;
  /** Specific tracking ID to send event to (targets specific service) */
  send_to?: string;
  /** Transport method for event delivery ("beacon" for reliability) */
  transport_type?: string;
  /** Callback function executed after event is sent */
  event_callback?: () => void;
  /** Custom dimensions and metrics */
  custom_parameter_1?: string;
  custom_parameter_2?: number;
  /** Any additional gtag event parameters */
  [key: string]: any;
}

Usage Examples:

Basic Event Tracking

// Guard against SSR - gtag only available in browser
if (typeof window !== "undefined" && window.gtag) {
  // Track button click
  window.gtag("event", "click", {
    event_category: "engagement",
    event_label: "header_cta_button",
  });
}

Conversion Tracking

// Track purchase conversion
if (typeof window !== "undefined" && window.gtag) {
  window.gtag("event", "purchase", {
    event_category: "ecommerce",
    event_label: "checkout_complete",
    value: 99.99,
    currency: "USD",
    transaction_id: "T12345",
  });
}

Targeted Event Tracking

// Send event to specific Google Ads account
if (typeof window !== "undefined" && window.gtag) {
  window.gtag("event", "conversion", {
    send_to: "AW-CONVERSION_ID/CONVERSION_LABEL",
    value: 50.0,
    currency: "USD",
  });
}

Event with Callback

// Track download with callback
if (typeof window !== "undefined" && window.gtag) {
  window.gtag("event", "download", {
    event_category: "file",
    event_label: "user_manual.pdf",
    transport_type: "beacon",
    event_callback: function () {
      console.log("Download event tracked successfully");
      // Additional logic after tracking
    },
  });
}

React Component Example

import React from "react";

export default function TrackedButton() {
  const handleClick = () => {
    // Custom event tracking
    if (typeof window !== "undefined" && window.gtag) {
      window.gtag("event", "click", {
        event_category: "ui_interaction",
        event_label: "newsletter_signup",
        transport_type: "beacon",
      });
    }
    
    // Your application logic
    console.log("Button clicked");
  };

  return (
    <button onClick={handleClick}>
      Subscribe to Newsletter
    </button>
  );
}

Custom Hook for Event Tracking

import { useCallback } from "react";

export function useGtagEvent() {
  const trackEvent = useCallback((eventName, parameters = {}) => {
    if (typeof window !== "undefined" && window.gtag) {
      window.gtag("event", eventName, parameters);
    }
  }, []);

  return trackEvent;
}

// Usage in component
export default function MyComponent() {
  const trackEvent = useGtagEvent();

  const handleFormSubmit = () => {
    trackEvent("form_submit", {
      event_category: "engagement",
      event_label: "contact_form",
    });
  };

  return <form onSubmit={handleFormSubmit}>...</form>;
}

Automatic Route Tracking

The plugin automatically tracks pageview events on route changes using Gatsby's onRouteUpdate browser API. This tracking only works in production mode.

// Automatic pageview tracking (handled internally by plugin)
// Fires on every Gatsby route change via onRouteUpdate
window.gtag("event", "page_view", {
  page_path: location.pathname + location.search + location.hash
});

Route Tracking Implementation Details

  • Async Timing: Uses requestAnimationFrame (or 32ms setTimeout fallback) to ensure React helmet updates complete
  • Path Filtering: Checks excluded paths against glob patterns using minimatch
  • Production Only: Route tracking is disabled in development and test environments

Route Tracking Configuration

Route tracking behavior can be configured via plugin options:

  • Path Exclusion: Use pluginConfig.exclude to skip tracking on specific paths (supports glob patterns)
  • Timing Delay: Use pluginConfig.delayOnRouteUpdate to add additional delay after React lifecycle
  • Do Not Track: Use pluginConfig.respectDNT to respect browser DNT settings during SSR injection

Common Event Types

Standard Google Analytics Events

// Engagement events
gtag("event", "click", { event_category: "engagement" });
gtag("event", "scroll", { event_category: "engagement" });
gtag("event", "search", { event_category: "engagement", search_term: "query" });

// Conversion events
gtag("event", "sign_up", { event_category: "conversion" });
gtag("event", "purchase", { event_category: "ecommerce", value: 99.99 });
gtag("event", "generate_lead", { event_category: "conversion" });

Google Ads Conversion Events

// Specific conversion tracking for Google Ads
gtag("event", "conversion", {
  send_to: "AW-CONVERSION_ID/CONVERSION_LABEL",
  value: 1.0,
  currency: "USD",
});

Additional Gtag Commands

Configuration Command

The plugin uses the config command internally to initialize tracking IDs:

// Plugin automatically executes config commands for each trackingId
gtag("config", "GA-TRACKING_ID", {
  optimize_id: "OPT_CONTAINER_ID",
  anonymize_ip: true,
  send_page_view: false // Plugin disables automatic pageviews
});

JavaScript Initialization

The js command initializes the gtag library (handled automatically by plugin):

// Plugin automatically executes during SSR
gtag("js", new Date());

SSR Safety

Always guard gtag calls against server-side rendering:

// ✅ Correct - guards against SSR
if (typeof window !== "undefined" && window.gtag) {
  window.gtag("event", "click", { event_category: "engagement" });
}

// ❌ Incorrect - will cause SSR errors
window.gtag("event", "click", { event_category: "engagement" });