Event tracking and monitoring

Basic concepts of event tracking and monitoring

November 19, 2024

Have you ever wonder how websites know what you're doing? How they know when you click a button or scroll to the bottom of the page? As a former marketer, I used to use Google Analytics (GA) to track user behavior on websites, did many data analysis and reports in order to understand user behavior and optimize marketing strategies, but I found out that sometimes the data was not accurate or not detailed or clear enough, and this was a big problem for me.

Now I am a frontend developer, I've got a chance to learn more about how websites work, and what's under the hood.

What is event tracking?

Event Tracking, the name itself is self-explanatory. It's the process of tracking user events on a website via scripts or tools, such as clicks, scrolls, form submissions, and the key metrics for business, such as what kind of product category users are interested in or how many users participated in a survey.

There're three main ways to track events:

  1. Manually add tracking code to the website: Implementing event tracking code to capture specific events.
  2. Automatically track with the help of browser APIs: Via DOM APIs.
  3. Third-party tracking tools.

What is monitoring?

The main purpose of monitoring is to ensure the stability of the system. Data like error logs, loading time, resource requests, etc. are collected and analyzed to identify and resolve issues.

Normally, there're 3 types of monitoring:

  1. Error monitoring: Capture JS errors, loading errors, etc.
  2. Performance monitoring: Collecting and analyzing data like loading time, resource request errors, etc. to identify and resolve issues.
  3. User experience monitoring: Collecting data like white screen, long task, etc.

Basic event tracking implementation

General Tracking function

This function is used to track general events, such as clicks, scrolls, form submissions, etc, and a "POST" request will be sent to the server to record the event.

In this function, I want to get the element that triggers the event,

// Here to define the type of the event
type EventType = 'click' | 'scroll' | 'formSubmission'
 
// Here to define the type of the button
type ButtonType = 'cta' | 'close' | 'submit'
 
// Here to define the details of the event
interface EventDetails {
  element: Element;
  buttonType: ButtonType;
  campaign: string;
  section: string;
  timeStamp: number;
  buttonPurpose: string;
  metadata?: {
    campaignId?: string;
    pageType?: string;
    url?: string;
    position?: number;  
  };
}
const trackEvent = (eventType: EventType, details: EventDetails) => {
  // "POST" request to the server to record the event, something like this:
  fetch('/api/trackEvent', {
    method: 'POST',
    body: JSON.stringify({ eventType, details })
  })
}

Let's say I want to track a "CTA" button, this data can be used to analyze the user behavior, and optimize the marketing campaign or website design.

<!-- esport signup website -->
<button id="ctaButton" type="button">Sign up</button>
// DOMContentLoaded is to make sure the DOM is loaded before adding event listeners
document.addEventListener("DOMContentLoaded", () => {
  // or you can declare a const variable to get the element
  // const ctaButton = document.getElementById("ctaButton");
  // Since id is unique, so we don't have to declare a const variable 
  ctaButton.addEventListener("click", () => {
    trackEvent("click", {
      element: ctaButton,
      buttonType: "cta",
      campaign: "esport-signup-2024-10-11",
      section: "section-1",、
      timeStamp: Date.now(),
      buttonPurpose: "signup",
      metadata: {
        campaignId: "E-signup",
        pageType: "marketing",
        url: window.location.href,
        position: 1,
      }
    })
  })
})

Basic monitoring implementation

Page load monitoring

Just like the general tracking function, we can create a general monitoring function to track the page load time or API request time.

window.addEventListener("load", () => {
  const pageLoad = Date.now();
  trackEvent("page_load", {
    duration: pageLoad,
    timeStamp: Date.now(),
  })
})

API request monitoring

For API monitoring, there're two stages that we can monitor:

  1. Before the request is sent.
  2. After the request is received.
const apiPerformance = (url:string) => {
  const startTime = performance.now();
  fetch(url).then((res) => res.json()).then((data) => {
    const duration  = performance.now() - startTime;
    trackEvent("api_request", {
      endpoint:url,
      duration,
      timeStamp: Date.now(),
    })
  })
}
apiPerformance("https://www.example.com/api/data")

JavaScript error monitoring

If we want to monitor the JavaScript errors, we can use the window.onerror event, when this event is triggered, execute the tracking function, for example:

<html>
  <body>
    <script>
      window.onerror = (message, source, lineno, colno, error) => {
        trackEvent("js_error", {
          message,
          source,
          lineno, 
          colno,
          timeStamp: Date.now(),
        });
      };
      "".push("123");
    </script>
  </body>
</html>

We can check the error in the console, it should show an object like this:

js error
Back to Blog 🏃🏽‍♀️