Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat: PostHog prod fixes + better linking for web/desktop
Richie McIlroyd650d350fbe4
diff --git a/apps/desktop/src/routes/(window-chrome)/(main).tsx b/apps/desktop/src/routes/(window-chrome)/(main).tsxindex 9ac726177..31fed2fa8 100644--- a/apps/desktop/src/routes/(window-chrome)/(main).tsx+++ b/apps/desktop/src/routes/(window-chrome)/(main).tsx@@ -24,7 +24,7 @@ import {import { createStore } from "solid-js/store";import Mode from "~/components/Mode";-import { trackEvent } from "~/utils/analytics";+import { identifyUser, trackEvent } from "~/utils/analytics";import {createCurrentRecordingQuery,createLicenseQuery,@@ -90,6 +90,24 @@ export default function () {createUpdateCheck();+ const auth = authStore.createQuery();++ onMount(async () => {+ if (auth.data?.user_id) {+ const authSessionId = `${auth.data.user_id}-${auth.data.expires}`;+ const trackedSession = localStorage.getItem("tracked_signin_session");++ if (trackedSession !== authSessionId) {+ console.log("New auth session detected, tracking sign in event");+ identifyUser(auth.data.user_id);+ trackEvent("user_signed_in", { platform: "desktop" });+ localStorage.setItem("tracked_signin_session", authSessionId);+ } else {+ console.log("Auth session already tracked, skipping sign in event");+ }+ }+ });+let unlistenFn: UnlistenFn;onCleanup(() => unlistenFn?.());const [initialize] = createResource(async () => {@@ -215,8 +233,6 @@ export default function () {),});- const auth = authStore.createQuery();-return (<div class="flex justify-center flex-col p-[1rem] gap-[0.75rem] text-[0.875rem] font-[400] bg-[--gray-50] h-full text-[--text-primary]">{initialize()}diff --git a/apps/desktop/src/utils/analytics.ts b/apps/desktop/src/utils/analytics.tsindex 28cc656d6..f7138067e 100644--- a/apps/desktop/src/utils/analytics.ts+++ b/apps/desktop/src/utils/analytics.ts@@ -4,26 +4,65 @@ import posthog from "posthog-js";const key = import.meta.env.VITE_POSTHOG_KEY as string;const host = import.meta.env.VITE_POSTHOG_HOST as string;+let isPostHogInitialized = false;+if (key && host) {- posthog.init(key, { api_host: host });+ try {+ posthog.init(key, {+ api_host: host,+ capture_pageview: false,+ loaded: (posthogInstance) => {+ isPostHogInitialized = true;+ }+ });+ console.log("PostHog initialization started");+ } catch (error) {+ console.error("Failed to initialize PostHog:", error);+ }}export function initAnonymousUser() {- if (!key || !host) return;- const anonymousId = localStorage.getItem("anonymous_id") ?? uuid();- localStorage.setItem("anonymous_id", anonymousId);- posthog.identify(anonymousId);+ if (!key || !host) {+ console.warn("Cannot initialize anonymous user - missing key or host");+ return;+ }++ try {+ const anonymousId = localStorage.getItem("anonymous_id") ?? uuid();+ localStorage.setItem("anonymous_id", anonymousId);+ posthog.identify(anonymousId);+ console.log("Anonymous user identified:", anonymousId);+ } catch (error) {+ console.error("Error initializing anonymous user:", error);+ }}export function identifyUser(userId: string, properties?: Record<string, any>) {- if (!key || !host) return;- const currentId = posthog.get_distinct_id();- if (currentId && currentId !== userId) {- posthog.alias(userId);+ if (!key || !host) {+ console.warn("Cannot identify user - missing key or host");+ return;}- posthog.identify(userId);- if (properties) {- posthog.people.set(properties);++ try {+ const currentId = posthog.get_distinct_id();+ const anonymousId = localStorage.getItem("anonymous_id");++ if (currentId !== userId) {+ if (anonymousId && currentId === anonymousId) {+ console.log(`Aliasing user ${userId} from anonymous ID ${anonymousId}`);+ posthog.alias(userId, anonymousId);+ }+ posthog.identify(userId);+ if (properties) {+ posthog.people.set(properties);+ }+ localStorage.removeItem("anonymous_id");+ console.log(`User identified: ${userId}`);+ } else {+ console.log(`User already identified as ${userId}`);+ }+ } catch (error) {+ console.error("Error identifying user:", error);}}@@ -31,6 +70,26 @@ export function trackEvent(eventName: string,properties?: Record<string, any>) {- if (!key || !host) return;- posthog.capture(eventName, properties);+ if (!key || !host) {+ console.warn("PostHog event not captured - missing key or host:", eventName);+ return;+ }++ try {+ if (!isPostHogInitialized) {+ console.warn(`PostHog not initialized yet, queuing event: ${eventName}`);+ // Queue the event to be sent when PostHog is initialized+ setTimeout(() => {+ console.log(`Retrying event ${eventName} after delay`);+ trackEvent(eventName, properties);+ }, 1000);+ return;+ }++ const eventProperties = { ...properties, platform: "desktop" };+ console.log(`Capturing event ${eventName}:`, eventProperties);+ posthog.capture(eventName, eventProperties);+ } catch (error) {+ console.error(`Error capturing event ${eventName}:`, error);+ }}diff --git a/apps/web/app/PosthogPageView.tsx b/apps/web/app/PosthogPageView.tsxindex 04ada49a3..632abe5d5 100644--- a/apps/web/app/PosthogPageView.tsx+++ b/apps/web/app/PosthogPageView.tsx@@ -12,13 +12,19 @@ function PostHogPageView(): null {// Track pageviewsuseEffect(() => {- if (pathname && posthog) {+ if (!pathname || !posthog) {+ return;+ }++ try {let url = window.origin + pathname;- if (searchParams.toString()) {+ if (searchParams?.toString()) {url = url + `?${searchParams.toString()}`;}posthog.capture("$pageview", { $current_url: url });+ } catch (error) {+ console.error("Error capturing pageview:", error);}}, [pathname, searchParams, posthog]);diff --git a/apps/web/app/api/settings/billing/subscribe/route.ts b/apps/web/app/api/settings/billing/subscribe/route.tsindex eb48f93e9..0def5ef7c 100644--- a/apps/web/app/api/settings/billing/subscribe/route.ts+++ b/apps/web/app/api/settings/billing/subscribe/route.ts@@ -5,6 +5,7 @@ import { eq } from "drizzle-orm";import { db } from "@cap/database";import { users } from "@cap/database/schema";import { clientEnv } from "@cap/env";+import posthog from "posthog-js";export async function POST(request: NextRequest) {console.log("Starting subscription process");@@ -35,6 +36,15 @@ export async function POST(request: NextRequest) {}try {+ // Track subscription initiated event+ if (typeof window !== 'undefined') {+ posthog.capture("subscription_initiated", {+ price_id: priceId,+ quantity: quantity,+ platform: "web"+ });+ }+if (!user.stripeCustomerId) {console.log("Creating new Stripe customer for user:", user.id);const customer = await stripe.customers.create({diff --git a/apps/web/app/api/webhooks/stripe/route.ts b/apps/web/app/api/webhooks/stripe/route.tsindex 3a5077a1e..73a9af076 100644--- a/apps/web/app/api/webhooks/stripe/route.ts+++ b/apps/web/app/api/webhooks/stripe/route.ts@@ -5,6 +5,7 @@ import { eq } from "drizzle-orm";import { NextResponse } from "next/server";import Stripe from "stripe";import { serverEnv } from "@cap/env";+import { PostHog } from 'posthog-node';const relevantEvents = new Set(["checkout.session.completed",@@ -192,6 +193,37 @@ export const POST = async (req: Request) => {.where(eq(users.id, dbUser.id));console.log("Successfully updated user in database");++ // Add server-side PostHog tracking here:+ try {+ // Initialize server-side PostHog+ const serverPostHog = new PostHog(+ process.env.NEXT_PUBLIC_POSTHOG_KEY || '',+ { host: process.env.NEXT_PUBLIC_POSTHOG_HOST || '' }+ );++ // Track subscription completed event+ serverPostHog.capture({+ distinctId: dbUser.id,+ event: 'subscription_completed',+ properties: {+ subscription_id: subscription.id,+ subscription_status: subscription.status,+ invite_quota: inviteQuota,+ price_id: subscription.items.data[0]?.price.id,+ quantity: inviteQuota,+ platform: 'web',+ is_first_subscription: true+ }+ });++ // Shutdown the client+ await serverPostHog.shutdown();+ console.log("Successfully tracked subscription event in PostHog");+ } catch (error) {+ console.error("Error tracking subscription in PostHog:", error);+ // Don't throw - we don't want to fail the webhook because of analytics+ }}if (event.type === "customer.subscription.updated") {diff --git a/apps/web/app/login/form.tsx b/apps/web/app/login/form.tsxindex 30b4eddeb..de23eabae 100644--- a/apps/web/app/login/form.tsx+++ b/apps/web/app/login/form.tsx@@ -7,6 +7,7 @@ import { useEffect, useState } from "react";import { toast } from "react-hot-toast";import { Input, Label } from "@cap/ui";import { NODE_ENV } from "@cap/env";+import { trackEvent } from "../utils/analytics";export function LoginForm() {const searchParams = useSearchParams();@@ -69,6 +70,7 @@ export function LoginForm() {}, [emailSent]);const handleGoogleSignIn = () => {+ trackEvent("auth_started", { method: "google", is_signup: true });signIn("google", {...(next && next.length > 0 ? { callbackUrl: next } : {}),});@@ -167,6 +169,10 @@ export function LoginForm() {if (!email) return;setLoading(true);+ trackEvent("auth_started", {+ method: "email",+ is_signup: !oauthError,+ });signIn("email", {email,redirect: false,@@ -177,6 +183,9 @@ export function LoginForm() {if (res?.ok && !res?.error) {setEmail("");setEmailSent(true);+ trackEvent("auth_email_sent", {+ email_domain: email.split("@")[1],+ });toast.success("Email sent - check your inbox!");} else {toast.error("Error sending email - try again?");diff --git a/apps/web/app/providers.tsx b/apps/web/app/providers.tsxindex f331fe9db..16ab0783a 100644--- a/apps/web/app/providers.tsx+++ b/apps/web/app/providers.tsx@@ -1,7 +1,7 @@"use client";import { useEffect } from "react";-import { identifyUser, initAnonymousUser } from "./utils/analytics";+import { identifyUser, initAnonymousUser, trackEvent } from "./utils/analytics";import posthog from "posthog-js";import { PostHogProvider as PHProvider } from "posthog-js/react";import { clientEnv } from "@cap/env";@@ -11,10 +11,26 @@ import { usePathname } from "next/navigation";export function PostHogProvider({ children }: { children: React.ReactNode }) {useEffect(() => {- posthog.init(clientEnv.NEXT_PUBLIC_POSTHOG_KEY as string, {- api_host: clientEnv.NEXT_PUBLIC_POSTHOG_HOST as string,- capture_pageview: false,- });+ const key = clientEnv.NEXT_PUBLIC_POSTHOG_KEY;+ const host = clientEnv.NEXT_PUBLIC_POSTHOG_HOST;++ if (key && host) {+ try {+ posthog.init(key, {+ api_host: host,+ capture_pageview: false,+ loaded: (posthogInstance) => {+ console.log("PostHog loaded and ready to capture events");+ },+ });+ } catch (error) {+ console.error("Failed to initialize PostHog:", error);+ }+ } else {+ console.error(+ "Missing PostHog environment variables. Events will not be tracked."+ );+ }}, []);return (@@ -65,7 +81,17 @@ export function AnalyticsProvider({if (!userId) {initAnonymousUser();} else {+ // Track if this is the first time a user is being identified+ const isNewUser = !localStorage.getItem("user_identified");+identifyUser(userId);++ if (isNewUser) {+ localStorage.setItem("user_identified", "true");+ trackEvent("user_signed_up");+ }++ trackEvent("user_signed_in");}}, [userId]);diff --git a/apps/web/app/utils/analytics.ts b/apps/web/app/utils/analytics.tsindex fa368786c..ddef1b6e8 100644--- a/apps/web/app/utils/analytics.ts+++ b/apps/web/app/utils/analytics.ts@@ -2,24 +2,42 @@ import * as uuid from "uuid";import posthog from "posthog-js";export function initAnonymousUser() {- const anonymousId = localStorage.getItem("anonymous_id") ?? uuid.v4();- localStorage.setItem("anonymous_id", anonymousId);- posthog.identify(anonymousId);+ try {+ if (!posthog || typeof posthog.identify !== 'function') {+ console.warn("PostHog not available for anonymous user");+ return;+ }++ const anonymousId = localStorage.getItem("anonymous_id") ?? uuid.v4();+ localStorage.setItem("anonymous_id", anonymousId);+ posthog.identify(anonymousId);+ } catch (error) {+ console.error("Error initializing anonymous user:", error);+ }}export function identifyUser(userId: string, properties?: Record<string, any>) {- const currentId = posthog.get_distinct_id();- const anonymousId = localStorage.getItem("anonymous_id");-- if (currentId !== userId) {- if (anonymousId && currentId === anonymousId) {- posthog.alias(userId, anonymousId);+ try {+ if (!posthog || typeof posthog.identify !== 'function') {+ console.warn("PostHog not available for user identification");+ return;}- posthog.identify(userId);- if (properties) {- posthog.people.set(properties);++ const currentId = posthog.get_distinct_id();+ const anonymousId = localStorage.getItem("anonymous_id");++ if (currentId !== userId) {+ if (anonymousId && currentId === anonymousId) {+ posthog.alias(userId, anonymousId);+ }+ posthog.identify(userId);+ if (properties) {+ posthog.people.set(properties);+ }+ localStorage.removeItem("anonymous_id");}- localStorage.removeItem("anonymous_id");+ } catch (error) {+ console.error("Error identifying user:", error);}}@@ -27,5 +45,14 @@ export function trackEvent(eventName: string,properties?: Record<string, any>) {- posthog.capture(eventName, { ...properties, platform: "web" });+ try {+ if (!posthog || typeof posthog.capture !== 'function') {+ console.warn(`PostHog not available for event: ${eventName}`);+ return;+ }++ posthog.capture(eventName, { ...properties, platform: "web" });+ } catch (error) {+ console.error(`Error tracking event ${eventName}:`, error);+ }}diff --git a/apps/web/package.json b/apps/web/package.jsonindex 5e0fdbc94..73e193531 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -64,6 +64,7 @@"next-mdx-remote": "^4.4.1","nextjs-cors": "^2.2.0","posthog-js": "^1.215.3",+ "posthog-node": "^4.11.2","react": "^18.2.0","react-dom": "^18.2.0","react-email": "^1.10.1",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b3678b55b..9e0c357e7 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -585,6 +585,9 @@ importers:posthog-js:specifier: ^1.215.3version: 1.215.3+ posthog-node:+ specifier: ^4.11.2+ version: 4.11.2react:specifier: ^18.2.0version: 18.3.1@@ -6715,6 +6718,9 @@ packages:resolution: {integrity: sha512-Mr2ZakwQ7XUAjp7pAwQWRhhK8mQQ6JAaNWSjmjxil0R8BPioMtQsTLOolGYkji1rcL++3dCqZA3zWqpT+9Ew6g==}engines: {node: '>=4'}+ resolution: {integrity: sha512-eBSYY4Y68NNlHbHBMdeDmKNtDgXWhQsJcGqzO3iLUM0GraQFSS9cVgPX5I9b3lbdFKyYoAEGAZF1DwhTaljNAw==}+resolution: {integrity: sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==}engines: {node: '>= 0.4'}@@ -11176,6 +11182,10 @@ packages:resolution: {integrity: sha512-vTk8/gyjbKP7EbDxWzo/GBCK7Ok7M6RTqEWOzRgIxCPf/KA5faFi5z1T4cRR1oPgcDqLeB1ZGa04Za/cPEHxgA==}+ resolution: {integrity: sha512-zzXCzatMyXcDdvcSJFoCV1lA+5LkT2f7dt1vj6I4S6QGUWlRMMu8krApseUY4/E8m2rhQlmR8BZU/2xXcgS7XQ==}+ engines: {node: '>=15.0.0'}+resolution: {integrity: sha512-JyhErpYOvBV1hEPwIxc/fHWXPfnEGdRKxc8gFdAZ7XV4tlzyzG847XAyEZqoDnynP88akM4eaHcSOzNcLWFguw==}peerDependencies:@@ -20017,6 +20027,14 @@ snapshots:+ dependencies:+ follow-redirects: 1.15.9+ form-data: 4.0.0+ proxy-from-env: 1.1.0+ transitivePeerDependencies:+ - debug+@@ -21743,7 +21761,7 @@ snapshots:'@typescript-eslint/parser': 5.62.0([email protected])([email protected])eslint: 8.57.1eslint-import-resolver-node: 0.3.9- eslint-import-resolver-typescript: 3.6.3(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])+ eslint-import-resolver-typescript: 3.6.3(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]([email protected]))([email protected])transitivePeerDependencies:- supports-color@@ -26081,6 +26099,12 @@ snapshots:preact: 10.24.1web-vitals: 4.2.3+ dependencies:+ axios: 1.8.4+ transitivePeerDependencies:+ - debug+dependencies:preact: 10.24.1