Single page application tracking with gtag.js

This guide describes how to use gtag.js to track pages on sites whose content is loaded dynamically without traditional full page loads.

Overview

A Single Page Application (SPA) is a web application or website that loads all of the resources required to navigate throughout the site on the first page load. As the user clicks links and interacts with the page, subsequent content is loaded dynamically. The application will often update the URL in the address bar to emulate traditional page navigation, but another full page request is never made.

The tracking snippet works well with traditional websites because the snippet code is run every single time the users load a new page. However, for a single page application where the site loads new page content dynamically rather than as full page loads, the gtag.js snippet code only runs once. This means subsequent (virtual) pageviews must be tracked manually as new content is loaded.

Tracking virtual pageviews

When your application loads content dynamically and updates the URL in the address bar, the page URL stored with gtag.js should be updated as well.

To update the page_path, modify the config for your property by specifying a value for the page_path parameter:

gtag('config', 'GA_TRACKING_ID', {'page_path': '/new-page.html'});

After you've added the new value for page_path, all subsequent events sent to that property will use that new value.

Handling multiple URLs for the same resource

Some SPAs only update the hash portion of the URL when loading content dynamically. This practice can lead to situations where many different page paths point to the same resource. In such cases, it's usually best to choose a canonical URL and only ever send that page_path value to Google Analytics.

For example, consider a website whose "About Us" page can be reached via any of the following URLs:

  • /about
  • /#/about
  • /home/#/about

To avoid duplication in your reports, it's best to track all of these pages with /about for the page_path.