Skip to Content
🚀 We just launched! Please star us on Github!
DocumentationSDKsJavaScript (Web)

JavaScript (Web)

Installation

npm
npm install @rybbit/js
yarn
yarn add @rybbit/js

Initialization

⚠️

rybbit.init() must be called once before any other tracking methods (pageview, event, etc.) can be used. Attempting to call other methods before init will result in errors or no tracking.

Syntax

rybbit.init(config: RybbitConfig);

Example

import rybbit from "@rybbit/js"; rybbit.init({ analyticsHost: "https://api.rybbit.io/api", siteId: "1", });

Configuration Options

Option (init)TypeDefaultDescription
analyticsHoststring-Required. URL of your Rybbit analytics instance (e.g., https://rybbit.yourdomain.com/api).
siteIdstring | number-Required. The Site ID for your website obtained from your Rybbit instance.
debouncenumber500Debounce time in milliseconds for tracking pageviews after route changes. Set to 0 to disable debouncing (track immediately).
autoTrackPageviewsbooleantrueTrack pageviews on initial load.
autoTrackSpaRoutesbooleantrueTrack pageviews on SPA navigation (if autoTrackPageviews is true).
trackQuerystringbooleantrueInclude the URL’s query string (e.g., ?utm_source=google) in the tracked querystring data.
trackOutboundLinksbooleantrueTrack clicks on anchor (<a>) tags that link to external domains.
trackHashRoutesbooleantrueTrack URL hash changes.
trackDataAttributesbooleantrueTrack clicks on elements with a data-rybbit-event attribute.
trackWebVitalsbooleanfalseTrack website performance metrics.
webVitalsTimeoutnumber20000Timeout in milliseconds for sending web vitals.
skipPatternsstring[][]Array of path patterns. Pageviews whose path matches any pattern will not be tracked. See Path Matching.
maskPatternsstring[][]Array of path patterns. For matching pageview paths, the original path will be replaced by the pattern itself in tracked data. See Path Matching.
debugbooleanfalseEnable detailed logging to the browser console.

Tracking Pageviews

Pageviews are tracked automatically if autoTrackPageviews is enabled (default). This includes the initial page load and subsequent route changes in Single Page Applications (SPAs) if autoTrackSpaRoutes is also enabled.

Syntax

rybbit.pageview(path?: string);

Parameters

  • path (string, Optional):
    • Replaces the detected URL path (window.location.pathname) and query string (window.location.search) for this specific pageview event.
    • Should start with a / (e.g., /virtual/my-custom-page).
    • If path includes its own query string (e.g., /virtual/step?id=123), that query string will be used for the event. If path has no query string, the querystring property will be empty.
    • skipPatterns and maskPatterns will be applied to path.

When to Use Manually

  • Automatic tracking disabled: If you set autoTrackPageviews: false during initialization.
  • Virtual Pageviews: In SPAs where a significant view change occurs without a URL change.
  • Specific Timing: If you need to ensure a pageview is tracked only after certain conditions are met.

Example

// Standard manual pageview (usually not needed if auto-tracking is on) rybbit.pageview(); // Example: Track a step within a multi-step modal function openUserDetailsModal(userId, step) { // ... logic to open and display the modal step ... rybbit.pageview(`/users/${userId}/modal/${step}`); } openUserDetailsModal("user-abc", "contact-info"); // Example: Track a virtual pageview with its own query parameters function showFilteredProductList(category, sortBy) { let virtualPathWithQuery = `/products/category/${category}?sort=${sortBy}&view=grid`; rybbit.pageview(virtualPathWithQuery); } showFilteredProductList("electronics", "price_desc");

Tracking Custom Events

Use custom events to track specific user interactions. Examples include button clicks, form submissions, or adding an item to a cart.

Programmatic Tracking

You can trigger events from your JavaScript code.

Syntax

rybbit.event(name: string, properties?: TrackProperties);

Parameters

  • name (string, Required): The name of the event you want to track.
  • properties (object, Optional): An object containing additional key-value pairs related to the event.

Example

// Track a simple button click document.getElementById("cta-button")?.addEventListener("click", () => { rybbit.event("cta_click"); }); // Track adding an item to a shopping cart with properties function addToCart(item) { // ... add item ... rybbit.event("add_to_cart", { itemId: item.id, itemName: item.name, price: item.price, quantity: 1 }); }

Declarative Tracking with Data Attributes

If trackDataAttributes is enabled (default), you can track events directly from your HTML. The SDK will automatically listen for clicks on elements with the data-rybbit-event attribute.

  • data-rybbit-event="<event-name>": This attribute makes the element trackable. The value is used as the event name.
  • data-rybbit-prop-<property-name>="<value>": You can add multiple properties to the event by using this attribute format. The SDK collects all attributes starting with data-rybbit-prop- and includes them as key-value pairs in the event data.

Example

<button data-rybbit-event="cta_click">Click Me</button> <button data-rybbit-event="add_to_cart" data-rybbit-prop-item_id="product-123" data-rybbit-prop-item_name="Classic T-Shirt" data-rybbit-prop-price="29.99" > Add to Cart </button>

Outbound links (links to external domains) are tracked automatically by default if trackOutboundLinks is enabled. The SDK attaches a global click listener to capture clicks on <a> tags with external href attributes.

Syntax

rybbit.outbound(url: string, text?: string, target?: string);

Parameters

  • url (string, Required): The destination URL of the outbound link.
  • text (string, Optional): The text content of the link. Defaults to "".
  • target (string, Optional): The target attribute of the link (e.g., _blank). Defaults to _self.

When to Use Manually

  • Automatic tracking disabled: If you set trackOutboundLinks: false during init.
  • Non-anchor elements: If you trigger navigation to an external site using JavaScript from an element that isn’t an <a> tag.

Example

// Manually track an outbound click triggered by a button document.getElementById("external-service-button")?.addEventListener("click", () => { let url = "https://external-service.com"; rybbit.outbound(url, "Visit External Service", "_blank"); // Optionally navigate after tracking window.open(url, "_blank"); });

User Identification

You can associate tracking events with a specific user ID. The ID is persisted in localStorage and will be attached to all subsequent tracking events for that user.

identify

Assigns a user ID.

rybbit.identify(userId: string);

Example:

// After a user logs in rybbit.identify("user-xzy-123");

clearUserId

Clears the stored user ID.

rybbit.clearUserId();

Example:

// When a user logs out rybbit.clearUserId();

getUserId

Retrieves the currently stored user ID.

rybbit.getUserId(): string | null;

Example:

let currentUserId = rybbit.getUserId(); console.log("Current Rybbit User ID:", currentUserId);

Cleanup

In Single Page Applications or other dynamic environments, you may need to manually clean up the listeners that the SDK sets up.

Syntax

rybbit.cleanup();

Path Matching

These options allow you to control which page paths are tracked and how they appear in your analytics data using wildcard patterns.

Wildcards

  • *: Matches any sequence of characters except the forward slash (/). Useful for matching single path segments.
  • **: Matches any sequence of characters including the forward slash (/). Useful for matching multiple path segments.

skipPatterns

If a page’s path matches any pattern in skipPatterns, the pageview for that path will not be sent.

Examples:

  • "/admin/*": Skips /admin/login, /admin/users, but not /admin/settings/profile.
  • "/admin/**": Skips /admin/login, /admin/users, and /admin/settings/profile.
  • "/users/*/profile": Skips /users/123/profile, /users/abc/profile, but not /users/123/settings.
Example skipPatterns in init
rybbit.init({ // ... other options skipPatterns: [ "/admin/**", // Skip all admin sections "/debug", // Skip exact /debug path "/users/*/settings" // Skip settings page for any user ] });

maskPatterns

If a page’s path matches a pattern in maskPatterns, the pageview will be sent, but the pathname will be replaced by the pattern string itself. This is useful for grouping similar pages or hiding sensitive IDs.

⚠️

If a path matches both a skipPatterns and a maskPatterns pattern, skipping takes priority.

Examples:

  • Pattern: "/users/*/profile"
    • /users/123/profile is tracked as pathname: "/users/*/profile".
  • Pattern: "/products/**"
    • /products/electronics/tv-123 is tracked as pathname: "/products/**".
Example maskPatterns in init
rybbit.init({ // ... other options maskPatterns: [ "/users/*/profile", // Group all user profile views "/orders/*" // Mask specific order IDs ] });
Last updated on
Rybbit
Copyright 2025 © Rybbit.