Skip to content

Commit

Permalink
refactor(saas): Manual capture pageview
Browse files Browse the repository at this point in the history
  • Loading branch information
alifarooq9 committed Apr 27, 2024
1 parent c06e2f4 commit 7e3f195
Showing 1 changed file with 30 additions and 2 deletions.
32 changes: 30 additions & 2 deletions starterkits/saas/src/components/posthog-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { env } from "@/env";
import { useSession } from "next-auth/react";
import { usePathname } from "next/navigation";
import posthog from "posthog-js";
import { PostHogProvider as CSPostHogProvider } from "posthog-js/react";
import { useEffect } from "react";
Expand All @@ -16,8 +17,6 @@ if (typeof window !== "undefined") {
loaded: (posthog) => {
if (env.NODE_ENV === "development") posthog.debug();
},
capture_pageview: true,
capture_pageleave: true,
});
}

Expand All @@ -28,6 +27,7 @@ type PostHogProviderProps = {
export function PosthogProvider({ children }: PostHogProviderProps) {
return (
<>
<CapturePageviewClient captureOnPathChange={true} />
<CSPostHogProvider client={posthog}>
<PosthogAuthWrapper>{children}</PosthogAuthWrapper>
</CSPostHogProvider>
Expand All @@ -51,3 +51,31 @@ function PosthogAuthWrapper({ children }: PostHogProviderProps) {

return children;
}

type CapturePageviewClientProps = {
captureOnPathChange?: boolean;
};

export function CapturePageviewClient({
captureOnPathChange = false,
}: CapturePageviewClientProps) {
const pathname = usePathname();

useEffect(() => {
const handleCapturePageview = () => posthog.capture("$pageview");

if (typeof window !== "undefined") {
window.addEventListener("load", handleCapturePageview);
}

return () => {
if (typeof window !== "undefined") {
window.removeEventListener("load", handleCapturePageview);
}
};

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [captureOnPathChange ? pathname : undefined]);

return null;
}

0 comments on commit 7e3f195

Please sign in to comment.