Open History to see the last commit
1import { PostHog } from 'posthog-node'
2
3let posthogClient: PostHog | null = null
4
5function configuration(): { host: string; token: string } | null {
6 const token = import.meta.env.VITE_PUBLIC_POSTHOG_PROJECT_TOKEN
7 const host = import.meta.env.VITE_PUBLIC_POSTHOG_HOST
8
9 if (!token || !host) {
10 if (import.meta.env.DEV) {
11 const missing = !token
12 ? 'VITE_PUBLIC_POSTHOG_PROJECT_TOKEN'
13 : 'VITE_PUBLIC_POSTHOG_HOST'
14 throw new Error(
15 `${missing} variable required by PostHog is missing or un-configured, this causes events to be silently missed. This error stops appearing once ${missing} is configured`,
16 )
17 }
18 return null
19 }
20
21 return { host, token }
22}
23
24export function getPostHogServerClient(): PostHog | null {
25 const config = configuration()
26 if (!config) return null
27
28 posthogClient ??= new PostHog(config.token, {
29 host: config.host,
30 flushAt: 1,
31 flushInterval: 0,
32 enableExceptionAutocapture: true,
33 })
34 return posthogClient
35}
36
37export function posthogRequestContext(request: Request): {
38 distinctId: string
39 sessionId?: string
40} {
41 const distinctId =
42 request.headers.get('X-PostHog-Distinct-Id') ?? `api:${crypto.randomUUID()}`
43 const sessionId = request.headers.get('X-PostHog-Session-Id') ?? undefined
44 return { distinctId, sessionId }
45}
46
47export async function captureServerEvent({
48 distinctId,
49 event,
50 properties,
51 request,
52}: {
53 distinctId?: string
54 event: string
55 properties?: Record<string, unknown>
56 request: Request
57}): Promise<void> {
58 const posthog = getPostHogServerClient()
59 if (!posthog) return
60
61 const context = posthogRequestContext(request)
62 try {
63 posthog.capture({
64 distinctId: distinctId ?? context.distinctId,
65 event,
66 properties: {
67 ...properties,
68 $session_id: context.sessionId,
69 source: 'api',
70 },
71 })
72 await posthog.flush()
73 } catch (error) {
74 console.error('PostHog event capture failed', event, error)
75 }
76}