Skip to content

Commit

Permalink
event-tracking: Disable if not in production or user opted-out
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaellehmkuhl committed Dec 9, 2024
1 parent c6c4ace commit 595c5d8
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/libs/external-telemetry/event-tracking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import ky from 'ky'
import localforage from 'localforage'
import posthog from 'posthog-js'

const cockpitTelemetryEnabledKey = 'cockpit-enable-usage-statistics-telemetry'

type EventPayload = {
/**
* The name of the event
Expand All @@ -21,6 +23,7 @@ type EventPayload = {
*
*/
class EventTracker {
private static enableEventTracking = false
static postHogApiUrl = 'https://us.i.posthog.com'
static postHogApiKey = 'phc_SfqVeZcpYHmhUn9NRizThxFxiI9fKqvjRjmBDB8ToRs'
static posthog: ReturnType<typeof posthog.init> | undefined = undefined
Expand All @@ -30,6 +33,16 @@ class EventTracker {
* Initialize the event tracking system
*/
constructor() {
// Only track usage statistics if the user has not opted out and the app is not in development mode
const isRunningInProduction = import.meta.env.PROD
const userHasExternalTelemetryEnabled = window.localStorage.getItem(cockpitTelemetryEnabledKey) === 'true'
EventTracker.enableEventTracking = isRunningInProduction && userHasExternalTelemetryEnabled

if (!EventTracker.enableEventTracking) {
console.info('Event tracking is disabled. Not initializing event tracker.')
return
}

if (!EventTracker.posthog) {
EventTracker.posthog = posthog.init(EventTracker.postHogApiKey, {
api_host: EventTracker.postHogApiUrl,
Expand All @@ -56,6 +69,8 @@ class EventTracker {
* @param {Record<string, unknown>} eventProperties - The properties of the event
*/
async capture(eventName: string, eventProperties?: Record<string, unknown>): Promise<void> {
if (!EventTracker.enableEventTracking) return

const eventId = `${eventName}-${Date.now()}`
const eventPayload: EventPayload = {
eventName,
Expand Down

0 comments on commit 595c5d8

Please sign in to comment.