()
| 134 | } |
| 135 | |
| 136 | export function initAnalytics() { |
| 137 | const { env, isProd, createClient, generateAnonymousId } = resolveDeps() |
| 138 | |
| 139 | if (!env.NEXT_PUBLIC_POSTHOG_API_KEY || !env.NEXT_PUBLIC_POSTHOG_HOST_URL) { |
| 140 | const error = new Error( |
| 141 | 'NEXT_PUBLIC_POSTHOG_API_KEY or NEXT_PUBLIC_POSTHOG_HOST_URL is not set', |
| 142 | ) |
| 143 | logAnalyticsError(error, { |
| 144 | stage: AnalyticsErrorStage.Init, |
| 145 | missingEnv: true, |
| 146 | }) |
| 147 | throw error |
| 148 | } |
| 149 | |
| 150 | // Generate anonymous ID for pre-login tracking |
| 151 | // PostHog will merge this with the real user ID via alias() when user logs in |
| 152 | anonymousId = generateAnonymousId() |
| 153 | identified = false |
| 154 | |
| 155 | try { |
| 156 | client = createClient(env.NEXT_PUBLIC_POSTHOG_API_KEY, { |
| 157 | host: env.NEXT_PUBLIC_POSTHOG_HOST_URL, |
| 158 | enableExceptionAutocapture: isProd, |
| 159 | }) |
| 160 | } catch (error) { |
| 161 | logAnalyticsError(error, { stage: AnalyticsErrorStage.Init }) |
| 162 | throw error |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | export async function flushAnalytics() { |
| 167 | if (!client) { |
no test coverage detected