Single-Page Application Tracking
What you'll learn: How to track route changes and virtual page views in SPAs without full page reloads.
The Challenge with SPAs
Traditional websites send full page requests to the server, triggering analytics automatically on each load. Single-Page Applications (SPAs), however, update content dynamically using JavaScript—the URL changes, but the browser never performs a full page reload. This means analytics tools like Google Analytics 4 won't automatically detect "page views" when users navigate between routes.
Think of it like flipping through a digital magazine app: you see different articles, but the app itself never closes and reopens. Without explicit tracking, analytics would think you only visited once.
Virtual Page Views
To solve this, you must manually track route changes as virtual page views. When your SPA's router detects a navigation event, you send a custom event to your analytics platform.
In a typical SPA framework, you'll hook into the router's navigation lifecycle:
// Example: Tracking route changes
router.afterEach((to, from) => {
// Send virtual page view to GA4
gtag('event', 'page_view', {
page_title: to.name,
page_location: window.location.href,
page_path: to.path
});
});
This tells Google Analytics 4 that a new "page" was viewed, even though no browser reload occurred.
Key Considerations
- Track the initial page load normally (GA4 handles this automatically)
- Track subsequent route changes as virtual page views using your router's hooks
- Include relevant metadata:
page_path,page_title, andpage_location - Avoid double-counting: don't track both the automatic load and a manual event for the same view
Key Takeaway: SPAs require manual virtual page view tracking because route changes don't trigger browser reloads—hook into your router's navigation events to send page_view events to your analytics platform.