Skip to content

Commit 5617362

Browse files
committed
fix analytics
1 parent c0961e4 commit 5617362

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

src/components/Analytics.tsx

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import {useEffect} from 'react';
44
import Script from 'next/script';
5-
import {usePathname, useSearchParams} from 'next/navigation';
65

76
declare global {
87
interface Window {
@@ -11,9 +10,6 @@ declare global {
1110
}
1211

1312
export function Analytics() {
14-
const pathname = usePathname();
15-
const searchParams = useSearchParams();
16-
1713
useEffect(() => {
1814
if (typeof window !== 'undefined') {
1915
const terminationEvent = 'onpagehide' in window ? 'pagehide' : 'unload';
@@ -30,15 +26,23 @@ export function Analytics() {
3026
}, []);
3127

3228
useEffect(() => {
33-
if (pathname && window.gtag) {
34-
const cleanedUrl = `${pathname}${
35-
searchParams?.toString() ? `?${searchParams.toString()}` : ''
36-
}`.split(/[\?\#]/)[0];
37-
window.gtag('event', 'pageview', {
38-
event_label: cleanedUrl,
39-
});
40-
}
41-
}, [pathname, searchParams]);
29+
// If only we had router events. But patching pushState is what Vercel Analytics does.
30+
// https://va.vercel-scripts.com/v1/script.debug.js
31+
const originalPushState = history.pushState;
32+
33+
history.pushState = function (...args) {
34+
const oldCleanedUrl = window.location.href.split(/[\?\#]/)[0];
35+
originalPushState.apply(history, args);
36+
const newCleanedUrl = window.location.href.split(/[\?\#]/)[0];
37+
if (oldCleanedUrl !== newCleanedUrl) {
38+
window?.gtag('set', 'page', newCleanedUrl);
39+
window?.gtag('send', 'pageview');
40+
}
41+
};
42+
return () => {
43+
history.pushState = originalPushState;
44+
};
45+
}, []);
4246

4347
return (
4448
<>

0 commit comments

Comments
 (0)