GTM does not report history change events
See original GitHub issueDescription
I’m trying to use the GTM via Partytown in Next.js. I have successfully loaded the scripts and got GTM to send the initial collect
request, but it does not report page_view
events after changing routes.
When testing the same setup without Partytown the collect
requests get sent properly.
Behaviour when loading GTM normally:
https://user-images.githubusercontent.com/9134970/165815764-c2279ce8-10d9-435b-a73f-da89e2c5126e.mov
Behaviour when loading GTM via Partytown:
https://user-images.githubusercontent.com/9134970/165816399-0d170266-c910-4cce-ad40-4da17f1a0221.mov
Expected behaviour
GTM loaded via Partytown detects route changes and sends appropriate collect
requests.
How to reproduce
Link to reproduction repo: https://github.com/MrPumpking/nextjs-partytown-gtag-bug
- The
main
branch contains pure Next.js setup with GTM. Paste your GTM measurement ID in the.env
file. - The
partytown
branch contains GTM loaded via Partytown.
When running each version, you can check the network tab in devtools for outgoing collect
requests.
GTM setup GTM is connected with GA4 using the standard Tag.
GA4 web stream has enabled enhanced measurement with the “Page changes based on browser history events” enabled.
Issue Analytics
- State:
- Created a year ago
- Reactions:1
- Comments:21 (3 by maintainers)
Top GitHub Comments
I spent some more time on this. Now I see that the problem is caused by
history.pushState
&history.replaceState
not being called inside worker.I added some more logic to Partytown’s internal LocationUpdate message handler. Now it detects how location has changed (either pushState, replaceState, pop state, etc). When needed it calls pushState or replaceState inside worker.
I already have a POC next.js app with proper history tracking 🎉
I will try to wrap it up and create MR sometime this week. There’s one ugly workaround in my code I would like to fix first.
I found the problem, I had to put the
gtag
on the window object (eg:window.gtag = function() {dataLayer.push(arguments)}
Then in _document where I’m setting the partown-config:Now partytown properly forwards
gtag()
calls to the worker.