aboutsummaryrefslogtreecommitdiff
path: root/packages/lib/posthog.tsx
blob: 438cef64ba480b6411ca2d12ee82cf651341bfbf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
"use client"

import { usePathname, useSearchParams } from "next/navigation"
import posthog from "posthog-js"
import { Suspense, useEffect } from "react"
import { useSession } from "./auth"

function PostHogPageTracking() {
	const pathname = usePathname()
	const searchParams = useSearchParams()

	// Page tracking
	useEffect(() => {
		if (pathname && posthog.__loaded) {
			let url = window.origin + pathname
			if (searchParams.toString()) {
				url = `${url}?${searchParams.toString()}`
			}

			// Extract page context for better tracking
			const pageContext = {
				$current_url: url,
				path: pathname,
				search_params: searchParams.toString(),
				page_type: getPageType(),
				org_slug: getOrgSlug(pathname),
			}

			posthog.capture("$pageview", pageContext)
		}
	}, [pathname, searchParams])

	return null
}

export function PostHogProvider({ children }: { children: React.ReactNode }) {
	const { data: session } = useSession()

	useEffect(() => {
		if (typeof window !== "undefined") {
			const posthogKey = process.env.NEXT_PUBLIC_POSTHOG_KEY
			const backendUrl =
				process.env.NEXT_PUBLIC_BACKEND_URL ?? "https://api.supermemory.ai"

			if (posthogKey) {
				posthog.init(posthogKey, {
					api_host: `${backendUrl}/orange`,
					ui_host: "https://us.i.posthog.com",
					person_profiles: "identified_only",
					capture_pageview: false,
					capture_pageleave: true,
				})
			} else {
				console.warn(
					"PostHog API key is not set. PostHog will not be initialized.",
				)
			}
		}
	}, [])

	// User identification
	useEffect(() => {
		if (session?.user && posthog.__loaded) {
			posthog.identify(session.user.id, {
				email: session.user.email,
				name: session.user.name,
				userId: session.user.id,
				createdAt: session.user.createdAt,
			})
		}
	}, [session?.user])

	return (
		<>
			<Suspense fallback={null}>
				{process.env.NODE_ENV === "production" && <PostHogPageTracking />}
			</Suspense>
			{children}
		</>
	)
}

function getPageType(): string {
	return "other"
}

function getOrgSlug(pathname: string): string | null {
	const match = pathname.match(/^\/([^/]+)\//)
	return match ? (match[1] ?? null) : null
}

export function usePostHog() {
	return posthog
}