Templates
Custom Events

Tracking Custom Events

To start instrumenting your own custom events, follow these two key steps:

  1. Create a Data Model: Define a new Data Model containing the properties you want to represent in your custom event.
  2. Instrument Your Application: Implement tracking in your existing application to send the custom event data to the Moose ingestion infrastructure you just set up.

Define a New Data Model

For client-side events, we recommend beginning with the global properties found in the PageViewRaw model. From there, you can then add custom properties relevant to the specific events you want to track.

Example: Button Click Event

If you want to track button click events, you could create a ButtonClickEvent Data Model with the following additional properties:

  • cta_copy (the text on the button clicked)
  • cta_target (the target link redirected by the button).

Add this ButtonClickEvent Data Model to your models.ts file:

moose/app/datamodels/models.ts
export interface ButtonClickEvent extends PageViewRaw {
  cta_copy: string; // Text on the button clicked
  cta_target: string; // Target link redirected by the button
}
💡

The extends PageViewRaw approach ensures you capture both the context (via common web analytics data fields) and the specific user interaction details for the event.

Save Your Changes

Moose will configure the same infrastructure components you already have for the PageViewRaw, but this time these components are typed to the schema for the new ButtonClickEvent model.

Validate that Moose configured all the infrastructure for you by opening a new terminal window and running the following command:

terminal
npx moose-cli ls
⚠️

Make sure you are in the moose project directory and your dev server is running (moose dev)

Sending Custom Events

If your custom event is being instrumented from the client side of your web app, you can leverage the same script.js file you used to capture page view events.

Example: Tracking Button Click Events

Add the following code to the onClick() event handler for the button you want to track:

Your Web App Client Code
...
// Capture the button text and target URL
window.MooseAnalytics.trackEvent("ButtonClickEvent", {
  cta_copy: BUTTON_COPY, // Dynamically capture the button text
  cta_target: BUTTON_HREF, // Capture the target URL
});
 
...
💡

Notes:

  • The first argument to trackEvent() corresponds to the name of the Data Model you defined for your custom event
  • The second argument is an object containing the properties unique to the ButtonClickEvent Data Model (in this case, cta_copy and cta_target)
  • The integrated script enriches the event data with common web analytics properties defined in the PageViewRaw model. This means you do not need to manually set these properties, as they are automatically appended to the event payload in the tracking script.