|
1 | | -import mixpanel from "mixpanel-browser"; |
| 1 | +import mixpanel from "mixpanel-browser" |
2 | 2 |
|
3 | | -const MIXPANEL_TOKEN = process.env.NEXT_PUBLIC_MIXPANEL_TOKEN!; |
| 3 | +const MIXPANEL_TOKEN = process.env.NEXT_PUBLIC_MIXPANEL_TOKEN |
| 4 | + |
| 5 | +let isMixpanelInitialized = false |
4 | 6 |
|
5 | 7 | export const initMixpanel = () => { |
6 | | - if (typeof window !== "undefined") { |
7 | | - mixpanel.init(MIXPANEL_TOKEN, { debug: process.env.NODE_ENV !== "production" }); |
8 | | - } |
9 | | -}; |
| 8 | + if (typeof window === "undefined" || isMixpanelInitialized) { |
| 9 | + return |
| 10 | + } |
10 | 11 |
|
11 | | -export const track = (event: string, props?: Record<string, any>) => { |
12 | | - if (typeof window !== "undefined") { |
13 | | - mixpanel.track(event, props); |
| 12 | + if (!MIXPANEL_TOKEN) { |
| 13 | + if (process.env.NODE_ENV !== "production") { |
| 14 | + console.warn("Mixpanel token is missing. Set NEXT_PUBLIC_MIXPANEL_TOKEN to enable analytics.") |
14 | 15 | } |
15 | | -}; |
| 16 | + return |
| 17 | + } |
| 18 | + |
| 19 | + mixpanel.init(MIXPANEL_TOKEN, { |
| 20 | + debug: process.env.NODE_ENV !== "production", |
| 21 | + ignore_dnt: true, |
| 22 | + }) |
| 23 | + |
| 24 | + isMixpanelInitialized = true |
| 25 | +} |
| 26 | + |
| 27 | +export const track = (event: string, props?: Record<string, unknown>) => { |
| 28 | + if (typeof window === "undefined" || !isMixpanelInitialized) { |
| 29 | + return |
| 30 | + } |
| 31 | + |
| 32 | + mixpanel.track(event, props) |
| 33 | +} |
16 | 34 |
|
17 | 35 | export const identify = (userId: string) => { |
18 | | - if (typeof window !== "undefined") { |
19 | | - mixpanel.identify(userId); |
20 | | - } |
21 | | -}; |
| 36 | + if (typeof window === "undefined" || !isMixpanelInitialized) { |
| 37 | + return |
| 38 | + } |
| 39 | + |
| 40 | + mixpanel.identify(userId) |
| 41 | +} |
| 42 | + |
| 43 | +export const trackPageView = (path: string, search?: string) => { |
| 44 | + track("Page View", { |
| 45 | + path, |
| 46 | + search: search || undefined, |
| 47 | + }) |
| 48 | +} |
0 commit comments