This commit is contained in:
Timo Knuth
2025-10-18 17:55:32 +02:00
parent 254e6490b8
commit 91b78cb284
65 changed files with 4481 additions and 1078 deletions

View 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();
}
}