GA4 claims to have a new improved measurement that can monitor page views automatically, but can it also detect client-side history router changes? (also known as SPA)
How can I implement it if it doesn't auto-detect?
Yes history changes are detected automatically and a pageview is send for each history push (change in state)
If you have enabled the Enhanced measurement in your GA4 property and selected Page changes based on browser history events
under Page Views settings (note this is the default setting if you haven't done any changes to your GA4 data stream)
gtag('config', 'TAG_ID', <parameters>);
The config code auto-detects history changes for SPA and sends the page_view
to GA4 on each history change.
If you have disabled option 1 above, then you need to manually send the page_view event based on history changes using a custom JS solution
How can I implement it if it doesn't auto-detect?
You need to send it manually. Generally, embed the following code in your router config to trigger as soon as the history state changes
gtag('event', 'page_view', {
page_title: '<Page Title>',
page_location: '<Page Location>'
});
Important: If you manually send page_view events, make sure enhanced measurement is configured correctly to avoid double counting pageviews on history state changes. Typically, this means disabling Page changes based on browser history events under the advanced settings of the Page views section.
Recommendation: I would recommend you to use Google Tag Manager if you are still relying on gtag.js
Official Google Documentation on measuring page views in GA4