From 08ff93225761492b0f16e278ba6b99fd51d6aca0 Mon Sep 17 00:00:00 2001 From: Thomas Camlong Date: Thu, 2 Oct 2025 16:20:25 +0200 Subject: [PATCH] feat: implement PostHog authentication hook - Create usePostHogAuth hook for automatic user identification - Add session-based identification tracking to prevent duplicate calls - Implement proper cleanup of PocketBase auth listeners - Follow PostHog best practices for identify timing - Integrate with centralized PostHog utility functions --- web/src/hooks/use-posthog-auth.ts | 42 +++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 web/src/hooks/use-posthog-auth.ts diff --git a/web/src/hooks/use-posthog-auth.ts b/web/src/hooks/use-posthog-auth.ts new file mode 100644 index 00000000..ba781444 --- /dev/null +++ b/web/src/hooks/use-posthog-auth.ts @@ -0,0 +1,42 @@ +"use client" + +import { usePostHog } from "posthog-js/react" +import { useEffect, useRef } from "react" +import { pb } from "@/lib/pb" +import { identifyUserInPostHog, resetPostHogIdentity } from "@/lib/posthog-utils" + +export function usePostHogAuth() { + const posthog = usePostHog() + const hasIdentified = useRef(false) + + useEffect(() => { + const checkAuthAndIdentify = () => { + if (pb.authStore.isValid && pb.authStore.model) { + // User is logged in, identify them in PostHog + // Only call identify once per session to avoid unnecessary calls + if (!hasIdentified.current) { + identifyUserInPostHog(posthog) + hasIdentified.current = true + } + } else { + // User is not logged in, reset PostHog identity + // This unlinks future events from the user (important for shared computers) + resetPostHogIdentity(posthog) + hasIdentified.current = false + } + } + + // Check auth state on mount + checkAuthAndIdentify() + + // Listen for auth changes + const unsubscribe = pb.authStore.onChange(() => { + checkAuthAndIdentify() + }) + + // Cleanup listener on unmount + return () => { + unsubscribe() + } + }, [posthog]) +}