Posthog behoben

This commit is contained in:
Timo Knuth
2025-12-11 11:40:38 +01:00
parent 8c5e2fa58e
commit 18f92c4285
8 changed files with 141 additions and 34 deletions

View File

@@ -1,58 +1,74 @@
'use client';
import { useEffect } from 'react';
import { useEffect, useState, useRef } 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();
const [isInitialized, setIsInitialized] = useState(false);
const initializationAttempted = useRef(false);
// Initialize PostHog once
useEffect(() => {
// Check if user has consented to analytics cookies
// Prevent double initialization in React Strict Mode
if (initializationAttempted.current) return;
initializationAttempted.current = true;
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();
}
},
});
const apiKey = process.env.NEXT_PUBLIC_POSTHOG_KEY;
const apiHost = process.env.NEXT_PUBLIC_POSTHOG_HOST;
if (!apiKey) {
console.warn('PostHog API key not configured');
return;
}
// Check if already initialized (using _loaded property)
if (!(posthog as any)._loaded) {
posthog.init(apiKey, {
api_host: apiHost || 'https://us.i.posthog.com',
person_profiles: 'identified_only',
capture_pageview: false, // Manual pageview tracking
capture_pageleave: true,
autocapture: true,
respect_dnt: true,
opt_out_capturing_by_default: false,
});
// Enable debug mode in development
if (process.env.NODE_ENV === 'development') {
posthog.debug();
}
// Set initialized immediately after init
setIsInitialized(true);
} else {
setIsInitialized(true); // Already loaded
}
}
// Cleanup on unmount
return () => {
if (cookieConsent === 'accepted') {
posthog.opt_out_capturing();
}
};
// NO cleanup function - PostHog should persist across page navigation
}, []);
// Track page views
// Track page views ONLY after PostHog is initialized
useEffect(() => {
const cookieConsent = localStorage.getItem('cookieConsent');
if (cookieConsent === 'accepted' && pathname) {
if (cookieConsent === 'accepted' && pathname && isInitialized) {
let url = window.origin + pathname;
if (searchParams && searchParams.toString()) {
url = url + `?${searchParams.toString()}`;
}
posthog.capture('$pageview', {
$current_url: url,
});
}
}, [pathname, searchParams]);
}, [pathname, searchParams, isInitialized]); // Added isInitialized dependency
return <>{children}</>;
}
@@ -62,7 +78,7 @@ export function PostHogProvider({ children }: { children: React.ReactNode }) {
*/
export function identifyUser(userId: string, traits?: Record<string, any>) {
const cookieConsent = localStorage.getItem('cookieConsent');
if (cookieConsent === 'accepted') {
if (cookieConsent === 'accepted' && (posthog as any)._loaded) {
posthog.identify(userId, traits);
}
}
@@ -72,7 +88,7 @@ export function identifyUser(userId: string, traits?: Record<string, any>) {
*/
export function trackEvent(eventName: string, properties?: Record<string, any>) {
const cookieConsent = localStorage.getItem('cookieConsent');
if (cookieConsent === 'accepted') {
if (cookieConsent === 'accepted' && (posthog as any)._loaded) {
posthog.capture(eventName, properties);
}
}
@@ -82,7 +98,7 @@ export function trackEvent(eventName: string, properties?: Record<string, any>)
*/
export function resetUser() {
const cookieConsent = localStorage.getItem('cookieConsent');
if (cookieConsent === 'accepted') {
if (cookieConsent === 'accepted' && (posthog as any)._loaded) {
posthog.reset();
}
}