Track Events

How to track custom events with Rybbit

The script exposes a global object window.rybbit with functions for manual tracking of events, as well as the ability to track events using data attributes on HTML elements.

Using Data Attributes

You can track custom events by adding data attributes to any HTML element:

<!-- Basic event tracking -->
<button data-rybbit-event="signup_clicked">Sign Up</button>

<!-- Event with custom properties -->
<button
  data-rybbit-event="purchase_click"
  data-rybbit-prop-product="premium"
  data-rybbit-prop-price="49.99"
>
  Buy Now
</button>

This approach requires no JavaScript and works on any clickable element.

Available Functions

window.rybbit.event(eventName, properties)

Tracks a custom event with optional properties.

  • eventName (String): The name of the custom event (max 256 characters).
  • properties (Object, Optional): A flat object of custom data. Serialized as JSON it must be at most 2048 characters; larger events are rejected, not truncated. Keep values to strings and numbers.
// Track a simple custom event
window.rybbit.event("Signup Button Clicked");

// Track a custom event with properties
window.rybbit.event("Item Added To Cart", {
  itemId: "PROD123",
  price: 49.99,
  category: "Clothing"
});

window.rybbit.pageview()

Tracks a pageview. Useful when automatic SPA navigation tracking is disabled in your site settings, or when you need to manually trigger a pageview.

// Track a pageview
window.rybbit.pageview();

window.rybbit.error(error, properties)

Reports an error you caught yourself as an error event. It goes through the same filtering as automatic error tracking: errors from other origins are skipped and identical errors are sent at most once per 60 seconds.

  • error (Error): The error object. Its name becomes the event name.
  • properties (Object, Optional): Extra context, such as filename, lineno, and colno, plus any custom fields.
try {
  riskyOperation();
} catch (err) {
  window.rybbit.error(err, { feature: "checkout" });
}

For identifying users, see Identify Users. For feature flags, see Feature Flags. Session replay can also be started and stopped manually with startSessionReplay(), stopSessionReplay(), and isSessionReplayActive().

TypeScript Support

Put this as rybbit.d.ts anywhere in your project to avoid having to do (window as any).rybbit.event() everywhere.

interface Rybbit {
    /**
     * Tracks a page view
     */
    pageview: () => void;

    /**
     * Tracks a custom event
     * @param name Name of the event
     * @param properties Optional properties for the event
     */
    event: (name: string, properties?: Record<string, any>) => void;

    /**
     * Reports a caught error as an error event
     * @param error The error object
     * @param properties Optional context (filename, lineno, colno, custom fields)
     */
    error: (error: Error, properties?: Record<string, any>) => void;

    /**
     * Sets a custom user ID for tracking logged-in users
     * @param userId The user ID to set (will be stored in localStorage)
     * @param traits Optional user metadata (email, name, custom fields)
     */
    identify: (userId: string, traits?: Record<string, unknown>) => void;

    /**
     * Updates traits for the currently identified user
     * @param traits User metadata to merge with existing traits
     */
    setTraits: (traits: Record<string, unknown>) => void;

    /**
     * Clears the stored user ID
     */
    clearUserId: () => void;

    /**
     * Gets the currently set user ID
     * @returns The current user ID or null if not set
     */
    getUserId: () => string | null;

    /**
     * Manually tracks outbound link clicks
     * @param url The URL of the outbound link
     * @param text Optional text content of the link
     * @param target Optional target attribute of the link
     */
    trackOutbound: (url: string, text?: string, target?: string) => void;

    /**
     * Evaluates a feature flag and returns its value. Reading a flag records a
     * feature flag exposure once per flag value/version.
     * @param key The flag key
     * @param fallback Value returned before flags resolve or if the flag doesn't exist
     * (a disabled flag returns false)
     */
    flag: <T = unknown>(key: string, fallback?: T) => T;

    /**
     * Returns the payload for a feature flag or its selected variant.
     * Use this for remote config and multivariate payloads.
     * @param key The flag key
     * @param fallback Value returned before flags resolve or if the flag is inactive
     */
    flagPayload: <T = unknown>(key: string, fallback?: T) => T;

    /**
     * Returns all evaluated flag values keyed by flag key
     */
    flags: () => Record<string, unknown>;

    /**
     * Returns all available flag payloads keyed by flag key
     */
    flagPayloads: () => Record<string, unknown>;

    /**
     * Runs a callback once the tracking script and feature flags are ready.
     * Use this before reading flags during page initialization.
     * @param callback Receives the ready rybbit instance
     */
    onReady: (callback: (rybbit: Rybbit) => void) => void;

    /**
     * Starts session replay recording, if session replay is enabled for the site
     */
    startSessionReplay: () => void;

    /**
     * Stops session replay recording
     */
    stopSessionReplay: () => void;

    /**
     * Returns whether session replay is currently recording
     */
    isSessionReplayActive: () => boolean;
}

declare global {
    interface Window {
        rybbit: Rybbit;
    }
}

export {};

Server-Side Tracking

For tracking events from server-side applications, mobile apps, or any platform outside the browser, you can use the HTTP API. This is useful for:

  • Server-side event tracking (Node.js, Python, Go, etc.)
  • Mobile app analytics (iOS, Android, Flutter)
  • Backend integrations and webhooks
  • Scenarios where the JavaScript snippet can't be used

See the API documentation for detailed examples in multiple languages including authentication, parameters, and rate limiting information.


Related Documentation:

On this page