Skip to content

Commit 7aae108

Browse files
authored
feat(posthog): added posthog for analytics (#1523)
* feat(posthog): added posthog for analytics * added envvars to env.ts
1 parent 980a6d8 commit 7aae108

File tree

6 files changed

+88
-2
lines changed

6 files changed

+88
-2
lines changed

apps/sim/instrumentation-client.ts

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,34 @@
55
* It respects the user's telemetry preferences stored in localStorage.
66
*
77
*/
8-
import { env } from './lib/env'
8+
import posthog from 'posthog-js'
9+
import { env, getEnv, isTruthy } from './lib/env'
10+
11+
// Initialize PostHog only if explicitly enabled
12+
if (isTruthy(getEnv('NEXT_PUBLIC_POSTHOG_ENABLED')) && getEnv('NEXT_PUBLIC_POSTHOG_KEY')) {
13+
posthog.init(getEnv('NEXT_PUBLIC_POSTHOG_KEY')!, {
14+
api_host: '/ingest',
15+
ui_host: 'https://us.posthog.com',
16+
person_profiles: 'identified_only',
17+
capture_pageview: true,
18+
capture_pageleave: true,
19+
capture_performance: true,
20+
session_recording: {
21+
maskAllInputs: false,
22+
maskInputOptions: {
23+
password: true,
24+
email: false,
25+
},
26+
recordCrossOriginIframes: false,
27+
recordHeaders: true,
28+
recordBody: true,
29+
},
30+
autocapture: true,
31+
capture_dead_clicks: true,
32+
persistence: 'localStorage+cookie',
33+
enable_heatmaps: true,
34+
})
35+
}
936

1037
if (typeof window !== 'undefined') {
1138
const TELEMETRY_STATUS_KEY = 'simstudio-telemetry-status'

apps/sim/lib/env.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ export const env = createEnv({
9090
TELEMETRY_ENDPOINT: z.string().url().optional(), // Custom telemetry/analytics endpoint
9191
COST_MULTIPLIER: z.number().optional(), // Multiplier for cost calculations
9292
LOG_LEVEL: z.enum(['DEBUG', 'INFO', 'WARN', 'ERROR']).optional(), // Minimum log level to display (defaults to ERROR in production, DEBUG in development)
93+
POSTHOG_ENABLED: z.boolean().optional(), // Enable PostHog analytics and session recording
9394

9495
// External Services
9596
BROWSERBASE_API_KEY: z.string().min(1).optional(), // Browserbase API key for browser automation
@@ -258,6 +259,8 @@ export const env = createEnv({
258259
// Analytics & Tracking
259260
NEXT_PUBLIC_GOOGLE_API_KEY: z.string().optional(), // Google API key for client-side API calls
260261
NEXT_PUBLIC_GOOGLE_PROJECT_NUMBER: z.string().optional(), // Google project number for Drive picker
262+
NEXT_PUBLIC_POSTHOG_ENABLED: z.boolean().optional(), // Enable PostHog analytics (client-side)
263+
NEXT_PUBLIC_POSTHOG_KEY: z.string().optional(), // PostHog project API key
261264

262265
// UI Branding & Whitelabeling
263266
NEXT_PUBLIC_BRAND_NAME: z.string().optional(), // Custom brand name (defaults to "Sim")
@@ -317,6 +320,8 @@ export const env = createEnv({
317320
NEXT_PUBLIC_EMAIL_PASSWORD_SIGNUP_ENABLED: process.env.NEXT_PUBLIC_EMAIL_PASSWORD_SIGNUP_ENABLED,
318321
NEXT_PUBLIC_E2B_ENABLED: process.env.NEXT_PUBLIC_E2B_ENABLED,
319322
NEXT_PUBLIC_COPILOT_TRAINING_ENABLED: process.env.NEXT_PUBLIC_COPILOT_TRAINING_ENABLED,
323+
NEXT_PUBLIC_POSTHOG_ENABLED: process.env.NEXT_PUBLIC_POSTHOG_ENABLED,
324+
NEXT_PUBLIC_POSTHOG_KEY: process.env.NEXT_PUBLIC_POSTHOG_KEY,
320325
NODE_ENV: process.env.NODE_ENV,
321326
NEXT_TELEMETRY_DISABLED: process.env.NEXT_TELEMETRY_DISABLED,
322327
},

apps/sim/lib/session/session-context.tsx

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import type React from 'react'
44
import { createContext, useCallback, useEffect, useMemo, useState } from 'react'
5+
import posthog from 'posthog-js'
56
import { client } from '@/lib/auth-client'
67

78
export type AppSession = {
@@ -52,6 +53,25 @@ export function SessionProvider({ children }: { children: React.ReactNode }) {
5253
loadSession()
5354
}, [loadSession])
5455

56+
useEffect(() => {
57+
if (isPending || typeof posthog.identify !== 'function') {
58+
return
59+
}
60+
61+
try {
62+
if (data?.user) {
63+
posthog.identify(data.user.id, {
64+
email: data.user.email,
65+
name: data.user.name,
66+
email_verified: data.user.emailVerified,
67+
created_at: data.user.createdAt,
68+
})
69+
} else {
70+
posthog.reset()
71+
}
72+
} catch {}
73+
}, [data, isPending])
74+
5575
const value = useMemo<SessionHookResult>(
5676
() => ({ data, isPending, error, refetch: loadSession }),
5777
[data, isPending, error, loadSession]

apps/sim/next.config.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,22 @@ const nextConfig: NextConfig = {
238238

239239
return redirects
240240
},
241+
async rewrites() {
242+
if (!isTruthy(env.POSTHOG_ENABLED)) {
243+
return []
244+
}
245+
246+
return [
247+
{
248+
source: '/ingest/static/:path*',
249+
destination: 'https://us-assets.i.posthog.com/static/:path*',
250+
},
251+
{
252+
source: '/ingest/:path*',
253+
destination: 'https://us.i.posthog.com/:path*',
254+
},
255+
]
256+
},
241257
}
242258

243259
export default nextConfig

apps/sim/package.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@
2828
"@aws-sdk/s3-request-presigner": "^3.779.0",
2929
"@azure/communication-email": "1.0.0",
3030
"@azure/storage-blob": "12.27.0",
31-
"@better-auth/stripe": "1.3.12",
3231
"@better-auth/sso": "1.3.12",
32+
"@better-auth/stripe": "1.3.12",
3333
"@browserbasehq/stagehand": "^2.0.0",
3434
"@cerebras/cerebras_cloud_sdk": "^1.23.0",
3535
"@e2b/code-interpreter": "^2.0.0",
@@ -93,6 +93,8 @@
9393
"openai": "^4.91.1",
9494
"papaparse": "5.5.3",
9595
"pdf-parse": "1.1.1",
96+
"posthog-js": "1.268.9",
97+
"posthog-node": "5.9.2",
9698
"prismjs": "^1.30.0",
9799
"react": "19.1.0",
98100
"react-colorful": "5.6.1",

bun.lock

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,8 @@
127127
"openai": "^4.91.1",
128128
"papaparse": "5.5.3",
129129
"pdf-parse": "1.1.1",
130+
"posthog-js": "1.268.9",
131+
"posthog-node": "5.9.2",
130132
"prismjs": "^1.30.0",
131133
"react": "19.1.0",
132134
"react-colorful": "5.6.1",
@@ -812,6 +814,8 @@
812814

813815
"@pkgjs/parseargs": ["@pkgjs/[email protected]", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="],
814816

817+
"@posthog/core": ["@posthog/[email protected]", "", {}, "sha512-f16Ozx6LIigRG+HsJdt+7kgSxZTHeX5f1JlCGKI1lXcvlZgfsCR338FuMI2QRYXGl+jg/vYFzGOTQBxl90lnBg=="],
818+
815819
"@protobufjs/aspromise": ["@protobufjs/[email protected]", "", {}, "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ=="],
816820

817821
"@protobufjs/base64": ["@protobufjs/[email protected]", "", {}, "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg=="],
@@ -1622,6 +1626,8 @@
16221626

16231627
"copy-anything": ["[email protected]", "", { "dependencies": { "is-what": "^4.1.8" } }, "sha512-yCEafptTtb4bk7GLEQoM8KVJpxAfdBJYaXyzQEgQQQgYrZiDp8SJmGKlYza6CYjEDNstAdNdKA3UuoULlEbS6w=="],
16241628

1629+
"core-js": ["[email protected]", "", {}, "sha512-L4NPsJlCfZsPeXukyzHFlg/i7IIVwHSItR0wg0FLNqYClJ4MQYTYLbC7EkjKYRLZF2iof2MUgN0EGy7MdQFChg=="],
1630+
16251631
"core-util-is": ["[email protected]", "", {}, "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="],
16261632

16271633
"cors": ["[email protected]", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g=="],
@@ -2564,6 +2570,12 @@
25642570

25652571
"postgres": ["[email protected]", "", {}, "sha512-Jtc2612XINuBjIl/QTWsV5UvE8UHuNblcO3vVADSrKsrc6RqGX6lOW1cEo3CM2v0XG4Nat8nI+YM7/f26VxXLw=="],
25662572

2573+
"posthog-js": ["[email protected]", "", { "dependencies": { "@posthog/core": "1.2.2", "core-js": "^3.38.1", "fflate": "^0.4.8", "preact": "^10.19.3", "web-vitals": "^4.2.4" }, "peerDependencies": { "@rrweb/types": "2.0.0-alpha.17", "rrweb-snapshot": "2.0.0-alpha.17" }, "optionalPeers": ["@rrweb/types", "rrweb-snapshot"] }, "sha512-ejK5/i0TUQ8I1SzaIn7xWNf5TzOjWquawpgjKit8DyucD3Z1yf7LTMtgCYZN8oRx9VjiPcP34fSk8YsWQmmkTQ=="],
2574+
2575+
"posthog-node": ["[email protected]", "", { "dependencies": { "@posthog/core": "1.2.2" } }, "sha512-oU7FbFcH5cn40nhP04cBeT67zE76EiGWjKKzDvm6IOm5P83sqM0Ij0wMJQSHp+QI6ZN7MLzb+4xfMPUEZ4q6CA=="],
2576+
2577+
"preact": ["[email protected]", "", {}, "sha512-5SYSgFKSyhCbk6SrXyMpqjb5+MQBgfvEKE/OC+PujcY34sOpqtr+0AZQtPYx5IA6VxynQ7rUPCtKzyovpj9Bpg=="],
2578+
25672579
"prettier": ["[email protected]", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-e9MewbtFo+Fevyuxn/4rrcDAaq0IYxPGLvObpQjiZBMAzB9IGmzlnG9RZy3FFas+eBMu2vA0CszMeduow5dIuQ=="],
25682580

25692581
"prismjs": ["[email protected]", "", {}, "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw=="],
@@ -3050,6 +3062,8 @@
30503062

30513063
"web-streams-polyfill": ["[email protected]", "", {}, "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug=="],
30523064

3065+
"web-vitals": ["[email protected]", "", {}, "sha512-r4DIlprAGwJ7YM11VZp4R884m0Vmgr6EAKe3P+kO0PPj3Unqyvv59rczf6UiGcb9Z8QxZVcqKNwv/g0WNdWwsw=="],
3066+
30533067
"webidl-conversions": ["[email protected]", "", {}, "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g=="],
30543068

30553069
"whatwg-encoding": ["[email protected]", "", { "dependencies": { "iconv-lite": "0.6.3" } }, "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ=="],
@@ -3502,6 +3516,8 @@
35023516

35033517
"postcss-nested/postcss-selector-parser": ["[email protected]", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg=="],
35043518

3519+
"posthog-js/fflate": ["[email protected]", "", {}, "sha512-FJqqoDBR00Mdj9ppamLa/Y7vxm+PRmNWA67N846RvsoYVMKB4q3y/de5PA7gUmRMYK/8CMz2GDZQmCRN1wBcWA=="],
3520+
35053521
"protobufjs/@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~7.10.0" } }, "sha512-DRh5K+ka5eJic8CjH7td8QpYEV6Zo10gfRkjHCO3weqZHWDtAaSTFtl4+VMqOJ4N5jcuhZ9/l+yy8rVgw7BQeQ=="],
35063522

35073523
"raw-body/iconv-lite": ["[email protected]", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-cf6L2Ds3h57VVmkZe+Pn+5APsT7FpqJtEhhieDCvrE2MK5Qk9MyffgQyuxQTm6BChfeZNtcOLHp9IcWRVcIcBQ=="],

0 commit comments

Comments
 (0)