Event tracking on Single Page Applications (SPA)

This documentation guides developers through integrating a custom event tracking system within React/Next.js applications. It focuses on capturing and analyzing user interactions to gain insights into application usage and behavior.

How SPAs different from MPAs

Multi-Page Applications (MPAs)

In traditional Multi-Page Applications, each user action that requires a new data view leads to a new request to the server, which then responds with a new HTML page. This process requires a full page reload, including re-fetching resources such as HTML, CSS, and JavaScript, which can result in longer page load times and a less responsive user experience. The architecture is straightforward, with each page representing a separate document, making it easier to design for SEO but potentially slower in user interaction responsiveness.

Key characteristics:

  • Each page corresponds to a new URL.
  • Server-side rendering of pages.
  • Full page reloads for fetching new content.
  • Clear SEO advantage due to distinct pages.

Single Page Applications (SPAs)

SPAs, on the other hand, load a single HTML page and dynamically update that page's content with JavaScript as the user interacts with the app. This model avoids page reloads by fetching only the necessary data in response to user actions and then rendering the new view in the browser. This approach significantly improves the user experience with smoother transitions and faster interactions. However, it introduces complexity in state management, routing, and SEO optimisation.

Key characteristics:

  • Single HTML page load with dynamic content updates.
  • Client-side rendering with JavaScript handling the UI updates.
  • Reduced server requests.
  • Complex state management and routing.
  • SEO optimisation requires additional strategies like server-side rendering or pre-rendering.

Divergence Points

  • MPAs reload the entire page from the server on most user actions, while SPAs reload only data, updating the UI dynamically.
  • In MPAs, the server renders pages, sending complete HTML to the browser. SPAs handle rendering in the browser, fetching data via APIs, and using JavaScript to build page content.
  • SPAs offer a more app-like experience with fancier feedback and transitions, whereas MPAs might feel slower due to full-page reloads.
  • MPAs have a straightforward SEO setup with distinct URLs for each page. SPAs require additional tools and configurations for SEO and for maintaining the app's different states.

Event-tracking strategies for SPAs

A specific event-tracking approach is crucial for single-page applications (SPAs) due to their dynamic nature and the absence of traditional page reloads. Here's a straightforward approach to event tracking in SPAs.

  1. Initialization:

    • Include your tracking library (like Intempt) in a centralized, framework-agnostic way (for example, in your app’s main entry point).
    • Configure it once so that it persists throughout the lifecycle of your SPA.
  2. General Event Listeners:

    • Set up global event listeners (e.g., for clicks, scrolls, or form submissions) using plain JavaScript.
    • Example for click tracking:
      document.addEventListener('click', function(event) {
        if (event.target.matches('.trackable')) {
          // Send event
        }
      });
      
  3. History API for Virtual Page Views:

    • Make sure that your framework fires the popstate event when the route changes, and call a similar callback:
     
        const handleRouteChange = (url) => {
          const popStateEvent = new PopStateEvent('popstate', { state: url });
          window.dispatchEvent(popStateEvent);
        };
    

  1. Reusable Tracking Function:

    • Abstract the tracking logic into a simple utility function:
      function trackEvent(eventName, payload) {
        if (window.intempt && typeof window.intempt.record === 'function') {
           window.intempt.record({eventTitle: eventName, data: eventBody});
        }
        // Optionally, log or queue events if the tracking library isn’t available yet.
      }
      
    • Use this function across your application wherever events need to be tracked.
  2. Integrating with Application-Specific Components:

    • For components or interactions like form submissions, button clicks, or user authentication events, call the trackEvent function with context-specific details.
    • For example, on form submission:
      document.querySelector('#loginForm').addEventListener('submit', function(e) {
        e.preventDefault();
        const email = e.target.email.value;
        window.intempt.identify({userId: email});
        trackEvent('form_submission', { form: 'Login', success: true, loginMethod: 'email' });
        // Continue with your login logic…
      });
      

  3. Performance and Debouncing:

    • Be mindful that global event listeners (especially scroll or resize events) fire frequently. Implement debouncing or throttling as needed to prevent performance issues.

Considerations

  • Test the event tracking in your application to ensure the tracking event is captured every time. Confirm the events show up in your Intempt analytics dashboard.
  • If the button can be clicked rapidly in succession, consider implementing throttling or debouncing to avoid flooding your analytics with too many events.

Summary

This guide provides a structured approach to tracking user interactions within Single Page Applications (SPAs). By implementing these tracking strategies, developers can gain deep insights into user behavior, session lengths, and engagement patterns, which are essential for optimising user experience and application performance.

For more information on script installation, visit the Intempt JavaScript SDK Installation Guide.