Next.js Discord

Discord Forum

Update url without triggering GA page_view event

Unanswered
German Shepherd Dog posted this in #help-forum
Open in Discord
German Shepherd DogOP
Hey, I'm updating query parameters in the url on one page of my website like this:
        const currentPath = window.location.pathname;
        const params = new URLSearchParams(window.location.search);
        params.set('data', encodedAttributes);

        const newUrl = `${currentPath}?${params.toString()}`;
        window.history.pushState(null, '', newUrl);


I'm using the GoogleAnalytics package from @next/third-parties/google, which triggers a page view event whenever the URL changes. This is recording lots of false page view events due to the code above. How can I update the URL without triggering page view events for Google Analytics?

14 Replies

first about your code, why aren't you using useRouter?
@Anay-208 | Ping in replies first about your code, why aren't you using useRouter?
German Shepherd DogOP
i did before like this:
// router.replace(?data=${encodedAttributes}, {scroll: false, shallow:true},)

but replaced it with the current version as an attempt to fix my issue (it didnt help but i didnt change the code back)
@Anay-208 | Ping in replies It might trigger a page visit because I think if a user changes a page it is supposed to count. Can I know what you’re trying to do exactly?
German Shepherd DogOP
the page is a calculator type tool where the user can adjust different parameters. i encode those parameters and store them in the query string so that people can bookmark the page or share it with other people easily
German Shepherd DogOP
im fairly certain that the way the third-parties package tracks page views is by simply looking for changes in the url since nextjs is a SPA. im just wondering if i can maybe overwrite that behaviour without re-creating the whole package
I'm not sure if it would resolve the issue, but this is a better practice I believe
you can just try it out
German Shepherd DogOP
i will, didnt know about nuqs ty
although i also believe this probably won't fix my issue
I also use PostHog for analytics and here i was simply able to discard all of those unwanted page views by returning early from the page view tracking if the query params contain 'data'. This sort of fix for GA would be enough for me
Oh, you can do that then
German Shepherd DogOP
yea fixed it by just not using the third-parties/google component and writing the GA scripts myself