diff --git a/src/components/PostHogPageView.tsx b/src/components/PostHogPageView.tsx index ed01a8c..96a43d3 100644 --- a/src/components/PostHogPageView.tsx +++ b/src/components/PostHogPageView.tsx @@ -1,6 +1,7 @@ import { useEffect } from 'react'; import { useLocation } from 'react-router-dom'; import { usePostHog } from 'posthog-js/react'; +import { api, isAuthenticated } from '../lib/api'; /** * Listens to React Router route changes and fires a PostHog $pageview event @@ -17,5 +18,29 @@ export default function PostHogPageView() { }); }, [location, posthog]); + // Identify user on load and on auth-change + useEffect(() => { + const identifyUser = async () => { + if (isAuthenticated()) { + try { + const profile = await api.getMe(); + posthog?.identify(profile.id, { + email: profile.email, + name: profile.full_name, + }); + } catch (err) { + console.error("Failed to identify user with backend", err); + } + } + }; + + // Run on initial load if returning user + identifyUser(); + + // Run whenever the token is set or cleared + window.addEventListener('auth-change', identifyUser); + return () => window.removeEventListener('auth-change', identifyUser); + }, [posthog]); + return null; } diff --git a/src/pages/AuthPage.tsx b/src/pages/AuthPage.tsx index 26e9b64..e826578 100644 --- a/src/pages/AuthPage.tsx +++ b/src/pages/AuthPage.tsx @@ -33,14 +33,6 @@ export default function AuthPage() { Promise.resolve().then(() => setStatus('processing')); setToken(accessToken); window.history.replaceState({}, '', '/auth'); - // Identify the user in PostHog using their JWT sub claim as the ID. - // The token is a JWT; we decode the payload to get the user ID. - try { - const payload = JSON.parse(atob(accessToken.split('.')[1])); - posthog?.identify(payload.sub, { email: payload.email }); - } catch { - // Not a JWT or malformed — skip identification silently - } navigate('/mode', { replace: true }); return; }