Skip to content

Commit

Permalink
Block duplicate Posthog page reports
Browse files Browse the repository at this point in the history
  • Loading branch information
pimterry committed Sep 6, 2024
1 parent ee9bbc5 commit a1da18f
Showing 1 changed file with 20 additions and 10 deletions.
30 changes: 20 additions & 10 deletions src/components/layout/posthog-page-view.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import { usePathname, useSearchParams } from 'next/navigation';
import { usePostHog } from 'posthog-js/react';
import { useEffect } from 'react';

let lastUrl: string | undefined = undefined;

export default function PostHogPageView(): null {
const pathname = usePathname();
const searchParams = useSearchParams();
Expand All @@ -13,17 +15,25 @@ export default function PostHogPageView(): null {
const { resolvedTheme } = useTheme();

useEffect(() => {
if (pathname && posthog) {
let url = window.origin + pathname;
if (searchParams.toString()) {
url = url + `?${searchParams.toString()}`;
}
posthog.capture('$pageview', {
$current_url: url,
theme: resolvedTheme
});
if (!pathname) return;

if (!posthog) return;

let url = window.origin + pathname;
if (searchParams.toString()) {
url = url + `?${searchParams.toString()}`;
}
}, [pathname, searchParams, posthog]);

// This can trigger with re-renders etc - so we actively block
// duplicate reports for the same URL.
if (url === lastUrl) return;
else lastUrl = url;

posthog.capture('$pageview', {
$current_url: url,
theme: resolvedTheme
});
}, [pathname, searchParams, posthog, resolvedTheme]);

return null;
}

0 comments on commit a1da18f

Please sign in to comment.