How to track pages in a single page application with Google Analytics?

A Single Page Application (SPA) loads all necessary resources on the first page load, then dynamically updates content without full page refreshes. This creates a challenge for Google Analytics, which traditionally tracks page views based on URL changes and page loads.

When users navigate within an SPA, the URL may change but no new page actually loads. Google Analytics needs to be manually informed about these navigation events to accurately track user behavior.

Setting Up Manual Page Tracking

To track page views in SPAs, you need to manually trigger Google Analytics events when the user navigates to different views. This involves two steps: updating the tracker and sending a pageview event.

Step 1: Update the Tracker

First, update the tracker with the new page information:

ga('set', 'page', '/new-page.html');

Step 2: Record Pageview

Send a pageview event immediately after updating the tracker:

ga('send', 'pageview');

Complete Implementation Example

Here's how to implement SPA tracking when route changes occur:

function trackPageView(pagePath) {
    // Update the tracker with new page
    ga('set', 'page', pagePath);
    
    // Send the pageview event
    ga('send', 'pageview');
}

// Example: Track when user navigates to different sections
function navigateToAbout() {
    // Update your SPA content here
    loadAboutContent();
    
    // Track the navigation
    trackPageView('/about');
}

function navigateToContact() {
    // Update your SPA content here  
    loadContactContent();
    
    // Track the navigation
    trackPageView('/contact');
}

Integration with Popular SPA Frameworks

Most SPA frameworks provide routing events that you can hook into:

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

function usePageTracking() {
    const location = useLocation();
    
    useEffect(() => {
        ga('set', 'page', location.pathname);
        ga('send', 'pageview');
    }, [location]);
}

// Vue.js Router example
router.afterEach((to) => {
    ga('set', 'page', to.fullPath);
    ga('send', 'pageview');
});

Best Practices

  • Always update the tracker before sending the pageview
  • Use meaningful page paths that reflect your SPA structure
  • Track both hash-based and history-based routing changes
  • Test your implementation to ensure accurate data collection

Conclusion

Tracking SPAs requires manual pageview events using ga('set', 'page', path) followed by ga('send', 'pageview'). Integrate these calls into your routing system to maintain accurate analytics data across your application.

Updated on: 2026-03-15T23:18:59+05:30

302 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements