Code Examples

Basic Usage

Track a Purchase

Track a basic purchase event when a user completes a transaction.

// Track a purchase with the built-in purchase event
document.getElementById('checkout-button').addEventListener('click', async () => {
  await pathing.send.purchase({
    product: "Pro Subscription",
    price: 99.99,
    currency: "USD",
    quantity: 1
  });
  
  // Continue with checkout process
  completeCheckout();
});

Track Form Submissions

Track when users submit a form on your website.

// Track form submissions
document.getElementById('contact-form').addEventListener('submit', (event) => {
  // Prevent default form submission
  event.preventDefault();
  
  // Get form data
  const form = event.target;
  const formData = new FormData(form);
  const name = formData.get('name');
  const email = formData.get('email');
  
  // Track the event
  pathing.send.raw('form_submit', {
    form_id: form.id,
    form_name: 'Contact Form',
    user_email_domain: email ? email.toString().split('@')[1] : null,
    has_name: !!name
  }).then(() => {
    // Submit the form after tracking
    form.submit();
  });
});

Track Video Playback

Monitor how users interact with video content.

// Track video playback
const video = document.getElementById('product-demo');

// Track play events
video.addEventListener('play', () => {
  pathing.send.playback({
    content: 'Product Demo Video',
    duration: video.duration,
    progress: video.currentTime / video.duration,
    action: 'play'
  });
});

// Track pause events
video.addEventListener('pause', () => {
  pathing.send.playback({
    content: 'Product Demo Video',
    duration: video.duration,
    progress: video.currentTime / video.duration,
    action: 'pause'
  });
});

// Track completion
video.addEventListener('ended', () => {
  pathing.send.playback({
    content: 'Product Demo Video',
    duration: video.duration,
    progress: 1.0,
    action: 'complete'
  });
});

Advanced Patterns

Declarative Tracking with HTML Attributes

Add tracking to elements using data attributes without writing JavaScript.

<!-- HTML -->
<button 
  id="signup-button"
  data-pathing-event="signup_click"
  data-pathing-source="header"
  data-pathing-plan="free"
>
  Sign Up Now
</button>

<!-- JavaScript to initialize tracking -->
<script>
  // Find all elements with data-pathing-event attributes
  document.querySelectorAll('[data-pathing-event]').forEach(el => {
    el.addEventListener('click', function() {
      // Get all data-pathing-* attributes
      const event = this.getAttribute('data-pathing-event');
      const payload = {};
      
      // Extract all data-pathing-* attributes (except event)
      for (const attr of this.attributes) {
        if (attr.name.startsWith('data-pathing-') && attr.name !== 'data-pathing-event') {
          const key = attr.name.replace('data-pathing-', '');
          payload[key] = attr.value;
        }
      }
      
      // Send the event
      pathing.send.raw(event, payload);
    });
  });
</script>

User Identification

Associate events with user identifiers for cohort analysis.

// Set user identity after login
function onUserLogin(user) {
  // Store user ID in local storage for persistence
  localStorage.setItem('pathing_user_id', user.id);
  
  // Track the login event with user properties
  pathing.send.raw('user_login', {
    user_id: user.id,
    user_email_domain: user.email.split('@')[1],
    account_type: user.accountType,
    login_method: 'email' // or 'google', 'github', etc.
  });
}

// Add user ID to all future events
pathing.addMiddleware(event => {
  const userId = localStorage.getItem('pathing_user_id');
  if (userId) {
    // Add to the event payload
    event.payload.user_id = userId;
  }
  return event;
});

SPA Router Integration

Track page views in single-page applications.

// Vue Router example
import { createRouter } from 'vue-router';

const router = createRouter({
  // router config
});

// Track page views
router.afterEach((to) => {
  pathing.send.raw('pageview', {
    path: to.path,
    title: document.title,
    isVirtualPageview: true,
    query_params: to.query
  });
});

// React Router example with hooks
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';

function PathroutingTracker() {
  const location = useLocation();
  
  useEffect(() => {
    pathing.send.raw('pageview', {
      path: location.pathname,
      title: document.title,
      isVirtualPageview: true,
      query_params: Object.fromEntries(new URLSearchParams(location.search))
    });
  }, [location]);
  
  return null;
}

Best Practices

Data Hygiene

Follow these principles for clean, useful analytics data:

  • Use consistent naming conventions for events
  • Use snake_case for event types and property keys
  • Document your event schema for your team's reference
  • Include timestamp data for events that might be sent later
  • Sanitize personal information (use domains instead of full emails)

Create a Tracking Plan

Document your tracking strategy to maintain consistency across your team.

A good tracking plan includes:

  • Event names and their triggers
  • Expected properties for each event
  • Example values for each property
  • Business questions each event helps answer