MVP
This commit is contained in:
88
src/components/PostHogProvider.tsx
Normal file
88
src/components/PostHogProvider.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
import { usePathname, useSearchParams } from 'next/navigation';
|
||||
import posthog from 'posthog-js';
|
||||
|
||||
export function PostHogProvider({ children }: { children: React.ReactNode }) {
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
useEffect(() => {
|
||||
// Check if user has consented to analytics cookies
|
||||
const cookieConsent = localStorage.getItem('cookieConsent');
|
||||
|
||||
// Only initialize PostHog if user has accepted cookies
|
||||
if (cookieConsent === 'accepted') {
|
||||
posthog.init('phc_97JBJVVQlqqiZuTVRHuBnnG9HasOv3GSsdeVjossizJ', {
|
||||
api_host: 'https://us.i.posthog.com',
|
||||
person_profiles: 'identified_only',
|
||||
capture_pageview: false, // We'll capture manually
|
||||
capture_pageleave: true,
|
||||
autocapture: true,
|
||||
// Privacy-friendly settings
|
||||
respect_dnt: true,
|
||||
opt_out_capturing_by_default: false,
|
||||
loaded: (posthog) => {
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
posthog.debug();
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Cleanup on unmount
|
||||
return () => {
|
||||
if (cookieConsent === 'accepted') {
|
||||
posthog.opt_out_capturing();
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Track page views
|
||||
useEffect(() => {
|
||||
const cookieConsent = localStorage.getItem('cookieConsent');
|
||||
|
||||
if (cookieConsent === 'accepted' && pathname) {
|
||||
let url = window.origin + pathname;
|
||||
if (searchParams && searchParams.toString()) {
|
||||
url = url + `?${searchParams.toString()}`;
|
||||
}
|
||||
posthog.capture('$pageview', {
|
||||
$current_url: url,
|
||||
});
|
||||
}
|
||||
}, [pathname, searchParams]);
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to identify user after login
|
||||
*/
|
||||
export function identifyUser(userId: string, traits?: Record<string, any>) {
|
||||
const cookieConsent = localStorage.getItem('cookieConsent');
|
||||
if (cookieConsent === 'accepted') {
|
||||
posthog.identify(userId, traits);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to track custom events
|
||||
*/
|
||||
export function trackEvent(eventName: string, properties?: Record<string, any>) {
|
||||
const cookieConsent = localStorage.getItem('cookieConsent');
|
||||
if (cookieConsent === 'accepted') {
|
||||
posthog.capture(eventName, properties);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to reset user on logout
|
||||
*/
|
||||
export function resetUser() {
|
||||
const cookieConsent = localStorage.getItem('cookieConsent');
|
||||
if (cookieConsent === 'accepted') {
|
||||
posthog.reset();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user