Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
📈 Refactor analytics code (#2030)
Luke Vella74de1a7cee93
diff --git a/apps/web/src/app/api/stripe/webhook/handlers/checkout/completed.ts b/apps/web/src/app/api/stripe/webhook/handlers/checkout/completed.tsindex 22dc9d246..a855c7127 100644--- a/apps/web/src/app/api/stripe/webhook/handlers/checkout/completed.ts+++ b/apps/web/src/app/api/stripe/webhook/handlers/checkout/completed.ts@@ -1,6 +1,7 @@import type { Stripe } from "@rallly/billing";-import { posthog } from "@rallly/posthog/server";+import { waitUntil } from "@vercel/functions";import { env } from "@/env";+import { PostHogClient } from "@/features/analytics/posthog";import { licenseCheckoutMetadataSchema } from "@/features/licensing/schema";import { licenseManager } from "@/features/licensing/server";import { getEmailClient } from "@/utils/emails";@@ -44,6 +45,8 @@ async function handleSelfHostedCheckoutSessionCompleted(seats,});+ const posthog = PostHogClient();+posthog?.capture({distinctId: email,event: "license_purchase",@@ -57,6 +60,10 @@ async function handleSelfHostedCheckoutSessionCompleted(},});+ if (posthog) {+ waitUntil(posthog.shutdown());+ }+if (!license || !license.data) {throw new Error(`Failed to create license for session: ${checkoutSession.id} - ${license?.error}`,diff --git a/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/created.ts b/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/created.tsindex e2ccc55c4..4171a8635 100644--- a/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/created.ts+++ b/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/created.ts@@ -1,7 +1,7 @@import type { Stripe } from "@rallly/billing";import { prisma } from "@rallly/database";-import { posthog } from "@rallly/posthog/server";-import { updateSpaceGroup } from "@/features/space/analytics";+import { waitUntil } from "@vercel/functions";+import { PostHogClient } from "@/features/analytics/posthog";import { subscriptionMetadataSchema } from "@/features/subscription/schema";import {getExpandedSubscription,@@ -91,8 +91,11 @@ export async function onCustomerSubscriptionCreated(event: Stripe.Event) {});});- updateSpaceGroup({- spaceId,+ const posthog = PostHogClient();++ posthog?.groupIdentify({+ groupType: "space",+ groupKey: spaceId,properties: {seatCount: quantity,tier,@@ -102,7 +105,7 @@ export async function onCustomerSubscriptionCreated(event: Stripe.Event) {posthog?.capture({distinctId: userId,uuid: event.id,- event: "upgrade",+ event: "subscription_create",properties: {interval,$set: {@@ -113,4 +116,8 @@ export async function onCustomerSubscriptionCreated(event: Stripe.Event) {space: spaceId,},});++ if (posthog) {+ waitUntil(posthog.shutdown());+ }}diff --git a/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/deleted.ts b/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/deleted.tsindex da626802a..a433c9f54 100644--- a/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/deleted.ts+++ b/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/deleted.ts@@ -1,8 +1,8 @@import type { Stripe } from "@rallly/billing";import { stripe } from "@rallly/billing";import { prisma } from "@rallly/database";-import { posthog } from "@rallly/posthog/server";-import { updateSpaceGroup } from "@/features/space/analytics";+import { waitUntil } from "@vercel/functions";+import { PostHogClient } from "@/features/analytics/posthog";import { subscriptionMetadataSchema } from "@/features/subscription/schema";export async function onCustomerSubscriptionDeleted(event: Stripe.Event) {@@ -49,8 +49,11 @@ export async function onCustomerSubscriptionDeleted(event: Stripe.Event) {});});- updateSpaceGroup({- spaceId,+ const posthog = PostHogClient();++ posthog?.groupIdentify({+ groupType: "space",+ groupKey: spaceId,properties: {tier: "hobby",},@@ -58,7 +61,7 @@ export async function onCustomerSubscriptionDeleted(event: Stripe.Event) {posthog?.capture({distinctId: userId,- event: "subscription cancel",+ event: "subscription_cancel",properties: {$set: {tier: "hobby",@@ -68,4 +71,8 @@ export async function onCustomerSubscriptionDeleted(event: Stripe.Event) {space: spaceId,},});++ if (posthog) {+ waitUntil(posthog.shutdown());+ }}diff --git a/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/updated.ts b/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/updated.tsindex b37458b22..bb3948f22 100644--- a/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/updated.ts+++ b/apps/web/src/app/api/stripe/webhook/handlers/customer-subscription/updated.ts@@ -1,7 +1,7 @@import type { Stripe } from "@rallly/billing";import { prisma } from "@rallly/database";-import { posthog } from "@rallly/posthog/server";-import { updateSpaceGroup } from "@/features/space/analytics";+import { waitUntil } from "@vercel/functions";+import { PostHogClient } from "@/features/analytics/posthog";import { subscriptionMetadataSchema } from "@/features/subscription/schema";import {getExpandedSubscription,@@ -89,8 +89,11 @@ export async function onCustomerSubscriptionUpdated(event: Stripe.Event) {});});- updateSpaceGroup({- spaceId,+ const posthog = PostHogClient();++ posthog?.groupIdentify({+ groupType: "space",+ groupKey: spaceId,properties: {seatCount: quantity,tier,@@ -100,10 +103,10 @@ export async function onCustomerSubscriptionUpdated(event: Stripe.Event) {posthog?.capture({distinctId: userId,uuid: event.id,- event: "subscription change",+ event: "subscription_update",properties: {- type: event.type,interval,+ quantity,$set: {tier,},@@ -112,4 +115,8 @@ export async function onCustomerSubscriptionUpdated(event: Stripe.Event) {space: spaceId,},});++ if (posthog) {+ waitUntil(posthog.shutdown());+ }}diff --git a/apps/web/src/app/api/user/verify-email-change/route.ts b/apps/web/src/app/api/user/verify-email-change/route.tsindex db0267c23..097ebaa51 100644--- a/apps/web/src/app/api/user/verify-email-change/route.ts+++ b/apps/web/src/app/api/user/verify-email-change/route.ts@@ -1,9 +1,10 @@import { stripe } from "@rallly/billing";import { prisma } from "@rallly/database";-import { posthog } from "@rallly/posthog/server";import * as Sentry from "@sentry/nextjs";+import { waitUntil } from "@vercel/functions";import type { NextRequest } from "next/server";import { NextResponse } from "next/server";+import { PostHogClient } from "@/features/analytics/posthog";import { getSession } from "@/lib/auth";import { decryptToken } from "@/utils/session";@@ -49,16 +50,6 @@ export const GET = async (request: NextRequest) => {},});- posthog?.capture({- event: "account_email_change_complete",- distinctId: payload.userId,- properties: {- $set: {- email: payload.toEmail,- },- },- });-try {if (user.customerId) {await stripe.customers.update(user.customerId, {@@ -69,6 +60,8 @@ export const GET = async (request: NextRequest) => {Sentry.captureException(error);}+ const posthog = PostHogClient();+posthog?.capture({event: "account_email_change_complete",distinctId: session.user.id,@@ -79,6 +72,10 @@ export const GET = async (request: NextRequest) => {},});+ if (posthog) {+ waitUntil(posthog.shutdown());+ }+return NextResponse.redirect(new URL("/settings/profile?emailChanged=true", request.url),);diff --git a/apps/web/src/auth/helpers/merge-user.ts b/apps/web/src/auth/helpers/merge-user.tsindex 24a4bf008..66bc485bf 100644--- a/apps/web/src/auth/helpers/merge-user.ts+++ b/apps/web/src/auth/helpers/merge-user.ts@@ -1,6 +1,7 @@import { prisma } from "@rallly/database";-import { posthog } from "@rallly/posthog/server";import * as Sentry from "@sentry/nextjs";+import { waitUntil } from "@vercel/functions";+import { PostHogClient } from "@/features/analytics/posthog";const getActiveSpaceForUser = async ({ userId }: { userId: string }) => {const spaceMember = await prisma.spaceMember.findFirst({@@ -56,11 +57,18 @@ export const mergeGuestsIntoUser = async (userId: string, guestId: string) => {}),]);});++ const posthog = PostHogClient();+posthog?.capture({distinctId: userId,event: "$merge_dangerously",properties: { alias: guestId },});++ if (posthog) {+ waitUntil(posthog.shutdown());+ }} catch (error) {Sentry.captureException(error);}@@ -114,12 +122,17 @@ export const linkAnonymousUser = async (]);});+ const posthog = PostHogClient();// Merge user identities in PostHogposthog?.capture({distinctId: authenticatedUserId,event: "$merge_dangerously",properties: { alias: anonymousUserId },});++ if (posthog) {+ waitUntil(posthog.shutdown());+ }} catch (error) {Sentry.captureException(error);}diff --git a/apps/web/src/features/analytics/posthog.ts b/apps/web/src/features/analytics/posthog.tsnew file mode 100644index 000000000..920167c86--- /dev/null+++ b/apps/web/src/features/analytics/posthog.ts@@ -0,0 +1,12 @@+import { PostHog } from "@rallly/posthog/server";+import { env } from "@/env";++export function PostHogClient() {+ if (!env.NEXT_PUBLIC_POSTHOG_API_KEY) return null;++ return new PostHog(env.NEXT_PUBLIC_POSTHOG_API_KEY, {+ host: env.NEXT_PUBLIC_POSTHOG_API_HOST,+ flushAt: 20,+ flushInterval: 10000,+ });+}diff --git a/apps/web/src/features/analytics/service.ts b/apps/web/src/features/analytics/service.tsdeleted file mode 100644index a470b9024..000000000--- a/apps/web/src/features/analytics/service.ts+++ /dev/null@@ -1,154 +0,0 @@-import { PostHog } from "@rallly/posthog/server";-import { toSnakeCaseKeys } from "es-toolkit";-import { env } from "@/env";-import type { PollEvent, PollGroupProperties } from "@/features/poll/analytics";--/**- * Analytics service that batches PostHog events for better performance- * Events are queued and sent in batches to avoid blocking mutations- */-export class AnalyticsService {- private posthog: PostHog | null = null;-- constructor() {- // Only initialize PostHog if we have the required environment variables- if (env.NEXT_PUBLIC_POSTHOG_API_HOST && env.NEXT_PUBLIC_POSTHOG_API_KEY) {- this.posthog = new PostHog(env.NEXT_PUBLIC_POSTHOG_API_KEY, {- host: env.NEXT_PUBLIC_POSTHOG_API_HOST,- flushAt: 20,- flushInterval: 10000,- });- }- }-- /**- * Track a poll event- * Events are batched and will be sent when flush() is called or when batch limits are reached- */- trackEvent(event: PollEvent): void {- if (!this.posthog) return;-- try {- // Handle automatic group updates based on event type- switch (event.type) {- case "poll_create":- // Set up initial group properties for new polls- this.setPoll(event.pollId, {- status: "live", // New polls start as live- participant_count: 0, // New polls start with 0 participants- comment_count: 0, // New polls start with 0 comments- ...toSnakeCaseKeys(event.properties),- });- break;-- case "poll_finalize":- // Update status to finalized- this.setPoll(event.pollId, {- status: "finalized",- });- break;-- case "poll_reopen":- case "poll_resume":- // Update status to live- this.setPoll(event.pollId, {- status: "live",- });- break;-- case "poll_pause":- // Update status to paused- this.setPoll(event.pollId, {- status: "paused",- });- break;-- case "poll_update_details":- case "poll_update_options":- case "poll_update_settings":- this.setPoll(event.pollId, toSnakeCaseKeys(event.properties));- break;-- case "poll_response_submit":- this.setPoll(event.pollId, {- participant_count: event.properties.totalResponses,- });- break;-- default:- break;- }-- const isGuest =- event.properties && "isGuest" in event.properties- ? event.properties.isGuest- : false;-- this.posthog.capture({- distinctId: event.userId,- event: event.type,- properties: {- poll_id: event.pollId,- ...toSnakeCaseKeys(event.properties ?? {}),- // Prevent person profile creation for anonymous/guest users- // This reduces costs while still allowing event tracking- ...(isGuest ? { $process_person_profile: false } : {}),- },- groups: {- poll: event.pollId,- ...("spaceId" in event ? { space: event.spaceId } : {}),- },- });- } catch (error) {- // Log error but don't throw - analytics should never break the application- console.error("Failed to track analytics event:", error);- }- }-- /**- * Update poll group properties with strong typing- * This is a strongly typed version of updateGroup specifically for polls- */- setPoll(pollId: string, properties: Partial<PollGroupProperties>): void {- if (!this.posthog) return;-- const { title, ...forwardProps } = properties;-- this.posthog.groupIdentify({- groupType: "poll",- groupKey: pollId,- properties: {- name: title,- ...forwardProps,- },- });- }-- /**- * Flush all pending events to PostHog- * This should be called after mutations complete to ensure events are sent- */- async flush(): Promise<void> {- if (!this.posthog) return;-- try {- await this.posthog.flush();- } catch (error) {- console.error("Failed to flush analytics events:", error);- }- }-- /**- * Shutdown the PostHog client- * This should be called when the service is no longer needed- */- async shutdown(): Promise<void> {- if (!this.posthog) return;-- try {- await this.posthog.shutdown();- } catch (error) {- console.error("Failed to shutdown analytics service:", error);- }- }-}diff --git a/apps/web/src/features/space/actions.ts b/apps/web/src/features/space/actions.tsindex ce413ae09..4faf890d7 100644--- a/apps/web/src/features/space/actions.ts+++ b/apps/web/src/features/space/actions.ts@@ -7,16 +7,6 @@ import { absoluteUrl } from "@rallly/utils/absolute-url";import { waitUntil } from "@vercel/functions";import { revalidatePath } from "next/cache";import { z } from "zod";-import {- trackInviteSent,- trackMemberJoin,- trackMemberLeaveSpace,- trackMemberRemoved,- trackSetActiveSpace,- trackSpaceCreated,- trackSpaceDeleted,- trackSpaceUpdated,-} from "@/features/space/analytics";import { getMember, getSpaceSeatCount } from "@/features/space/data";import { createSpace } from "@/features/space/mutations";import { memberRoleSchema } from "@/features/space/schema";@@ -26,6 +16,7 @@ import { AppError } from "@/lib/errors";import {authActionClient,createRateLimitMiddleware,+ posthogMiddleware,spaceActionClient,} from "@/lib/safe-action/server";import {@@ -76,10 +67,16 @@ export const setActiveSpaceAction = authActionClientspaceId: parsedInput.spaceId,});- trackSetActiveSpace({- spaceId: parsedInput.spaceId,- userId: ctx.user.id,- name: space.name,+ ctx.posthog?.capture({+ distinctId: ctx.user.id,+ event: "space_set_active",+ properties: {+ space_id: parsedInput.spaceId,+ space_name: space.name,+ },+ groups: {+ space: parsedInput.spaceId,+ },});});@@ -88,6 +85,7 @@ export const createSpaceAction = authActionClientactionName: "space_create",}).use(createRateLimitMiddleware(5, "1h"))+ .use(posthogMiddleware).inputSchema(z.object({name: z.string().min(1).max(100),@@ -99,7 +97,27 @@ export const createSpaceAction = authActionClientownerId: ctx.user.id,});- trackSpaceCreated({ space, userId: ctx.user.id });+ ctx.posthog?.groupIdentify({+ groupType: "space",+ groupKey: space.id,+ properties: {+ name: space.name,+ memberCount: 1,+ seatCount: 1,+ tier: "hobby",+ },+ });++ ctx.posthog?.capture({+ distinctId: ctx.user.id,+ event: "space_create",+ properties: {+ space_name: space.name,+ },+ groups: {+ space: space.id,+ },+ });revalidatePath("/", "layout");@@ -164,9 +182,15 @@ export const deleteSpaceAction = spaceActionClient},});- trackSpaceDeleted({- spaceId: space.id,- userId: ctx.user.id,+ ctx.posthog?.capture({+ distinctId: ctx.user.id,+ event: "space_delete",+ properties: {+ space_id: space.id,+ },+ groups: {+ space: space.id,+ },});revalidatePath("/", "layout");@@ -284,11 +308,15 @@ export const inviteMemberAction = spaceActionClient},});- trackInviteSent({- spaceId: ctx.space.id,- userId: ctx.user.id,- role: parsedInput.role,- email: parsedInput.email,+ ctx.posthog?.capture({+ distinctId: ctx.user.id,+ event: "space_member_invite",+ properties: {+ role: parsedInput.role,+ },+ groups: {+ space: ctx.space.id,+ },});return {@@ -373,10 +401,15 @@ export const acceptInviteAction = authActionClientconsole.warn("Failed to update user's active space");}- trackMemberJoin({- spaceId: parsedInput.spaceId,- userId: ctx.user.id,- memberCount,+ ctx.posthog?.capture({+ distinctId: ctx.user.id,+ event: "space_member_join",+ properties: {+ member_count: memberCount,+ },+ groups: {+ space: parsedInput.spaceId,+ },});});@@ -419,10 +452,16 @@ export const removeMemberAction = spaceActionClient},});- trackMemberRemoved({- spaceId: member.spaceId,- userId: deletedMember.userId,- memberCount,+ ctx.posthog?.capture({+ distinctId: ctx.user.id,+ event: "space_member_remove",+ properties: {+ member_count: memberCount,+ deleted_member_user_id: deletedMember.userId,+ },+ groups: {+ space: member.spaceId,+ },});});@@ -547,10 +586,15 @@ export const updateSpaceAction = spaceActionClientawait deleteImageFromS3(oldImage);}- trackSpaceUpdated({- spaceId: ctx.space.id,- userId: ctx.user.id,- name: parsedInput.name,+ ctx.posthog?.capture({+ distinctId: ctx.user.id,+ event: "space_update",+ properties: {+ space_name: parsedInput.name,+ },+ groups: {+ space: ctx.space.id,+ },});});@@ -753,10 +797,15 @@ export const leaveSpaceFromAccountAction = authActionClient},});- trackMemberLeaveSpace({- spaceId: parsedInput.spaceId,- userId: ctx.user.id,- memberCount,+ ctx.posthog?.capture({+ distinctId: ctx.user.id,+ event: "space_member_leave",+ properties: {+ member_count: memberCount,+ },+ groups: {+ space: parsedInput.spaceId,+ },});});@@ -835,9 +884,14 @@ export const leaveSpaceAction = spaceActionClient},});- trackMemberLeaveSpace({- spaceId: ctx.space.id,- userId: ctx.user.id,- memberCount,+ ctx.posthog?.capture({+ distinctId: ctx.user.id,+ event: "space_member_leave",+ properties: {+ member_count: memberCount,+ },+ groups: {+ space: ctx.space.id,+ },});});diff --git a/apps/web/src/features/space/analytics.ts b/apps/web/src/features/space/analytics.tsdeleted file mode 100644index 41c0c39ad..000000000--- a/apps/web/src/features/space/analytics.ts+++ /dev/null@@ -1,271 +0,0 @@-import { posthog } from "@rallly/posthog/server";-import { toSnakeCaseKeys } from "es-toolkit";-import type { SpaceTier } from "@/features/space/schema";--export function updateSpaceGroup({- spaceId,- properties,-}: {- spaceId: string;- properties: {- seatCount?: number;- memberCount?: number;- tier?: SpaceTier;- name?: string;- deleted?: boolean;- deletedAt?: Date;- };-}) {- posthog?.groupIdentify({- groupType: "space",- groupKey: spaceId,- properties: toSnakeCaseKeys(properties),- });-}--export function trackSpaceCreated({- space,- userId,-}: {- space: {- id: string;- name: string;- };- userId: string;-}): void {- if (!posthog) return;-- updateSpaceGroup({- spaceId: space.id,- properties: {- name: space.name,- memberCount: 1,- seatCount: 1,- tier: "hobby",- },- });-- posthog.capture({- distinctId: userId,- event: "space_create",- properties: {- space_id: space.id,- space_name: space.name,- },- groups: {- space: space.id,- },- });-}--export function trackSpaceUpdated({- spaceId,- name,- userId,-}: {- spaceId: string;- userId: string;- name?: string;-}): void {- if (!posthog) return;-- updateSpaceGroup({- spaceId,- properties: {- name,- },- });-- posthog.capture({- distinctId: userId,- event: "space_update",- properties: {- space_id: spaceId,- name: name,- },- groups: {- space: spaceId,- },- });-}--export function trackSpaceDeleted({- spaceId,- userId,-}: {- spaceId: string;- userId: string;-}): void {- if (!posthog) return;-- updateSpaceGroup({- spaceId,- properties: {- deleted: true,- deletedAt: new Date(),- },- });-- posthog.capture({- distinctId: userId,- event: "space_delete",- properties: {- space_id: spaceId,- },- groups: {- space: spaceId,- },- });-}--export function trackMemberJoin({- spaceId,- memberCount,- userId,-}: {- spaceId: string;- memberCount: number;- userId: string;-}): void {- if (!posthog) return;-- updateSpaceGroup({- spaceId,- properties: {- memberCount,- },- });-- posthog.capture({- distinctId: userId,- event: "space_member_join",- properties: {- space_id: spaceId,- member_count: memberCount,- },- groups: {- space: spaceId,- },- });-}--export function trackMemberRemoved({- spaceId,- memberCount,- userId,-}: {- spaceId: string;- memberCount: number;- userId: string;-}): void {- if (!posthog) return;-- updateSpaceGroup({- spaceId,- properties: {- memberCount,- },- });-- posthog.capture({- distinctId: userId,- event: "space_member_remove",- properties: {- space_id: spaceId,- member_count: memberCount,- },- groups: {- space: spaceId,- },- });-}--export function trackInviteSent({- spaceId,- role,- userId,- email,-}: {- spaceId: string;- role: string;- userId: string;- email: string;-}): void {- if (!posthog) return;-- posthog?.capture({- distinctId: userId,- event: "space_member_invite",- properties: {- space_id: spaceId,- role,- email,- },- groups: {- space: spaceId,- },- });-}--export function trackMemberLeaveSpace({- spaceId,- memberCount,- userId,-}: {- spaceId: string;- memberCount: number;- userId: string;-}): void {- if (!posthog) return;-- updateSpaceGroup({- spaceId,- properties: {- memberCount,- },- });-- posthog.capture({- distinctId: userId,- event: "space_member_leave",- properties: {- space_id: spaceId,- member_count: memberCount,- },- groups: {- space: spaceId,- },- });-}--export function trackSetActiveSpace({- spaceId,- userId,- name,-}: {- spaceId: string;- userId: string;- name: string;-}) {- if (!posthog) return;-- updateSpaceGroup({- spaceId,- properties: {- name,- },- });-- posthog.capture({- distinctId: userId,- event: "space_set_active",- properties: {- $set: {- active_space_id: spaceId,- },- },- groups: {- space: spaceId,- },- });-}diff --git a/apps/web/src/features/space/client.tsx b/apps/web/src/features/space/client.tsxindex 5c088b63e..0a65d4076 100644--- a/apps/web/src/features/space/client.tsx+++ b/apps/web/src/features/space/client.tsx@@ -1,5 +1,6 @@"use client";+import { usePostHog } from "@rallly/posthog/client";import React from "react";import type { MemberAbility } from "@/features/space/member/ability";import { defineAbilityForMember } from "@/features/space/member/ability";@@ -55,6 +56,15 @@ export const SpaceProvider = ({[data, userId],);+ const posthog = usePostHog();++ React.useEffect(() => {+ posthog?.group("space", data.id, {+ name: data.name,+ tier: data.tier,+ });+ }, [posthog, data.id, data.name, data.tier]);+return (<SpaceContext.Provider value={value}>{children}</SpaceContext.Provider>);diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.tsindex aca8042db..f99ce345e 100644--- a/apps/web/src/lib/auth.ts+++ b/apps/web/src/lib/auth.ts@@ -1,6 +1,6 @@import { prisma } from "@rallly/database";-import { posthog } from "@rallly/posthog/server";import { absoluteUrl } from "@rallly/utils/absolute-url";+import { waitUntil } from "@vercel/functions";import type { BetterAuthPlugin } from "better-auth";import { APIError, betterAuth } from "better-auth";import { prismaAdapter } from "better-auth/adapters/prisma";@@ -21,6 +21,7 @@ import {} from "@/auth/helpers/merge-user";import { isTemporaryEmail } from "@/auth/helpers/temp-email-domains";import { env } from "@/env";+import { PostHogClient } from "@/features/analytics/posthog";import { createSpace } from "@/features/space/mutations";import { getTranslation } from "@/i18n/server";import { getLocale } from "@/i18n/server/get-locale";@@ -87,10 +88,14 @@ export const authLib = betterAuth({});},onPasswordReset: async ({ user }) => {+ const posthog = PostHogClient();posthog?.capture({distinctId: user.id,event: "password_reset",});+ if (posthog) {+ waitUntil(posthog.shutdown());+ }},},emailVerification: {@@ -246,9 +251,25 @@ export const authLib = betterAuth({},});+ const posthog = PostHogClient();+if (existingUser) {// create a space for the user- await createSpace({ name: "Personal", ownerId: user.id });+ const space = await createSpace({+ name: "Personal",+ ownerId: user.id,+ });++ posthog?.groupIdentify({+ groupType: "space",+ groupKey: space.id,+ properties: {+ name: space.name,+ memberCount: 1,+ seatCount: 1,+ tier: "hobby",+ },+ });}posthog?.capture({@@ -265,6 +286,10 @@ export const authLib = betterAuth({},},});++ if (posthog) {+ waitUntil(posthog.shutdown());+ }},},},@@ -292,13 +317,17 @@ export const authLib = betterAuth({// Only track login events for non-anonymous users// Anonymous users shouldn't trigger login events or create person profilesif (user && !user.isAnonymous) {+ const posthog = PostHogClient();+posthog?.capture({distinctId: session.userId,event: "login",- properties: {- method: user.lastLoginMethod,- },+ properties: { method: user.lastLoginMethod },});++ if (posthog) {+ waitUntil(posthog.shutdown());+ }}},},diff --git a/apps/web/src/lib/safe-action/server.ts b/apps/web/src/lib/safe-action/server.tsindex 788cac22f..ebd6ba993 100644--- a/apps/web/src/lib/safe-action/server.ts+++ b/apps/web/src/lib/safe-action/server.ts@@ -1,11 +1,11 @@import "server-only";-import { PostHog } from "@rallly/posthog/server";import * as Sentry from "@sentry/nextjs";import { waitUntil } from "@vercel/functions";import { createMiddleware, createSafeActionClient } from "next-safe-action";import z from "zod";import { getCurrentUser, getCurrentUserSpace } from "@/auth/data";+import { PostHogClient } from "@/features/analytics/posthog";import { defineAbilityForSpace } from "@/features/space/ability";import { defineAbilityForMember } from "@/features/space/member/ability";import { defineAbilityFor } from "@/features/user/ability";@@ -13,14 +13,8 @@ import { AppError } from "@/lib/errors";import type { Duration } from "@/lib/rate-limit";import { rateLimit } from "@/lib/rate-limit";-const posthogMiddleware = createMiddleware().define(async ({ next }) => {- const posthog = process.env.NEXT_PUBLIC_POSTHOG_API_KEY- ? new PostHog(process.env.NEXT_PUBLIC_POSTHOG_API_KEY, {- host: process.env.NEXT_PUBLIC_POSTHOG_API_HOST,- flushAt: 20,- flushInterval: 10000,- })- : null;+export const posthogMiddleware = createMiddleware().define(async ({ next }) => {+ const posthog = PostHogClient();const result = await next({ctx: {diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.tsindex e861fadfb..4d66ee9fa 100644--- a/apps/web/src/trpc/routers/polls.ts+++ b/apps/web/src/trpc/routers/polls.ts@@ -1,6 +1,5 @@import type { PollStatus } from "@rallly/database";import { prisma } from "@rallly/database";-import { posthog } from "@rallly/posthog/server";import { absoluteUrl, shortUrl } from "@rallly/utils/absolute-url";import { nanoid } from "@rallly/utils/nanoid";import { TRPCError } from "@trpc/server";@@ -196,7 +195,7 @@ export const polls = router({]);if (isFlaggedContent) {- posthog?.capture({+ ctx.posthog?.capture({distinctId: ctx.user.id,event: "flagged_content",properties: {@@ -303,11 +302,26 @@ export const polls = router({}}- ctx.analytics.trackEvent({- type: "poll_create",- userId: ctx.user.id,- pollId: poll.id,- spaceId: poll.spaceId ?? undefined,+ ctx.posthog?.groupIdentify({+ groupType: "poll",+ groupKey: poll.id,+ properties: {+ name: poll.title,+ status: poll.status,+ is_guest: ctx.user.isGuest,+ created_at: poll.createdAt,+ participant_count: 0,+ comment_count: 0,+ option_count: poll.options.length,+ has_location: !!location,+ has_description: !!description,+ timezone: input.timeZone,+ },+ });++ ctx.posthog?.capture({+ event: "poll_create",+ distinctId: ctx.user.id,properties: {title: poll.title,optionCount: poll.options.length,@@ -320,6 +334,10 @@ export const polls = router({requireParticipantEmail: poll.requireParticipantEmail,isGuest: ctx.user.isGuest,},+ groups: {+ poll: poll.id,+ ...(poll.spaceId ? { space: poll.spaceId } : {}),+ },});revalidatePath("/", "layout");@@ -352,7 +370,7 @@ export const polls = router({]);if (isFlaggedContent) {- posthog?.capture({+ ctx.posthog?.capture({distinctId: ctx.user.id,event: "flagged_content",properties: {@@ -469,42 +487,46 @@ export const polls = router({input.requireParticipantEmail !== undefined;if (hasDetailsUpdate) {- ctx.analytics.trackEvent({- type: "poll_update_details",- userId: ctx.user.id,- pollId,+ ctx.posthog?.capture({+ event: "poll_update_details",+ distinctId: ctx.user.id,properties: {title: updatedPoll.title,- hasLocation: !!updatedPoll.location,- hasDescription: !!updatedPoll.description,- isGuest: ctx.user.isGuest,+ has_location: !!updatedPoll.location,+ has_description: !!updatedPoll.description,+ is_guest: ctx.user.isGuest,+ },+ groups: {+ poll: pollId,},});}if (hasOptionsUpdate) {- ctx.analytics.trackEvent({- type: "poll_update_options",- userId: ctx.user.id,- pollId,+ ctx.posthog?.capture({+ event: "poll_update_options",+ distinctId: ctx.user.id,properties: {- optionCount: updatedPoll._count.options,- isGuest: ctx.user.isGuest,+ option_count: updatedPoll._count.options,+ },+ groups: {+ poll: pollId,},});}if (hasSettingsUpdate) {- ctx.analytics.trackEvent({- type: "poll_update_settings",- userId: ctx.user.id,- pollId,+ ctx.posthog?.capture({+ event: "poll_update_settings",+ distinctId: ctx.user.id,properties: {- disableComments: !!updatedPoll.disableComments,- hideParticipants: !!updatedPoll.hideParticipants,- hideScores: !!updatedPoll.hideScores,- requireParticipantEmail: !!updatedPoll.requireParticipantEmail,- isGuest: ctx.user.isGuest,+ disable_comments: !!updatedPoll.disableComments,+ hide_participants: !!updatedPoll.hideParticipants,+ hide_scores: !!updatedPoll.hideScores,+ require_participant_email: !!updatedPoll.requireParticipantEmail,+ },+ groups: {+ poll: pollId,},});}@@ -526,12 +548,11 @@ export const polls = router({});// Track poll deletion analytics- ctx.analytics.trackEvent({- type: "poll_delete",- userId: ctx.user.id,- pollId,- properties: {- isGuest: ctx.user.isGuest,+ ctx.posthog?.capture({+ event: "poll_delete",+ distinctId: ctx.user.id,+ groups: {+ poll: pollId,},});@@ -574,10 +595,15 @@ export const polls = router({});// Track poll watch analytics- ctx.analytics.trackEvent({- type: "poll_watch",- userId: ctx.user.id,- pollId: input.pollId,+ ctx.posthog?.capture({+ event: "poll_watch",+ distinctId: ctx.user.id,+ properties: {+ is_guest: ctx.user.isGuest,+ },+ groups: {+ poll: input.pollId,+ },});}),unwatch: privateProcedure@@ -601,10 +627,12 @@ export const polls = router({});// Track poll unwatch analytics- ctx.analytics.trackEvent({- type: "poll_unwatch",- userId: ctx.user.id,- pollId: input.pollId,+ ctx.posthog?.capture({+ event: "poll_unwatch",+ distinctId: ctx.user.id,+ groups: {+ poll: input.pollId,+ },});}}),@@ -1029,14 +1057,16 @@ export const polls = router({);}- ctx.analytics.trackEvent({- type: "poll_finalize",- pollId: poll.id,- userId: ctx.user.id,+ ctx.posthog?.capture({+ event: "poll_finalize",+ distinctId: ctx.user.id,properties: {- attendeeCount: attendees.length,- daysSinceCreated: dayjs().diff(poll.createdAt, "day"),- participantCount: poll.participants.length,+ attendee_count: attendees.length,+ days_since_created: dayjs().diff(poll.createdAt, "day"),+ participant_count: poll.participants.length,+ },+ groups: {+ poll: poll.id,},});@@ -1078,10 +1108,12 @@ export const polls = router({}});- ctx.analytics.trackEvent({- type: "poll_reopen",- pollId: input.pollId,- userId: ctx.user.id,+ ctx.posthog?.capture({+ event: "poll_reopen",+ distinctId: ctx.user.id,+ groups: {+ poll: input.pollId,+ },});revalidatePath("/", "layout");@@ -1112,12 +1144,11 @@ export const polls = router({},});- ctx.analytics.trackEvent({- type: "poll_pause",- pollId: input.pollId,- userId: ctx.user.id,- properties: {- isGuest: ctx.user.isGuest,+ ctx.posthog?.capture({+ event: "poll_pause",+ distinctId: ctx.user.id,+ groups: {+ poll: input.pollId,},});}),@@ -1220,12 +1251,11 @@ export const polls = router({});// Track poll resume analytics- ctx.analytics.trackEvent({- type: "poll_resume",- userId: ctx.user.id,- pollId: input.pollId,- properties: {- isGuest: ctx.user.isGuest,+ ctx.posthog?.capture({+ event: "poll_resume",+ distinctId: ctx.user.id,+ groups: {+ poll: input.pollId,},});}),diff --git a/apps/web/src/trpc/routers/polls/comments.ts b/apps/web/src/trpc/routers/polls/comments.tsindex 9708f2dbf..21579bd4a 100644--- a/apps/web/src/trpc/routers/polls/comments.ts+++ b/apps/web/src/trpc/routers/polls/comments.ts@@ -172,13 +172,14 @@ export const comments = router({}// Track comment addition analytics- ctx.analytics.trackEvent({- type: "poll_comment_add",- userId: ctx.user.id,- pollId,+ ctx.posthog?.capture({+ distinctId: ctx.user.id,+ event: "poll_comment_add",properties: {- commentId: newComment.id,- isGuest: ctx.user.isGuest,+ is_guest: ctx.user.isGuest,+ },+ groups: {+ poll: pollId,},});@@ -225,12 +226,11 @@ export const comments = router({// Track comment deletion analyticsif (comment) {- ctx.analytics.trackEvent({- type: "poll_comment_delete",- userId: ctx.user.id,- pollId: comment.pollId,- properties: {- commentId,+ ctx.posthog?.capture({+ distinctId: ctx.user.id,+ event: "poll_comment_delete",+ groups: {+ poll: comment.pollId,},});}diff --git a/apps/web/src/trpc/routers/polls/participants.ts b/apps/web/src/trpc/routers/polls/participants.tsindex bf65c351a..1359b3061 100644--- a/apps/web/src/trpc/routers/polls/participants.ts+++ b/apps/web/src/trpc/routers/polls/participants.ts@@ -153,12 +153,14 @@ export const participants = router({},});- ctx.analytics.trackEvent({- type: "poll_response_delete",- userId: ctx.user.id,- pollId: participant.pollId,+ ctx.posthog?.capture({+ distinctId: ctx.user.id,+ event: "poll_response_delete",properties: {- participantId,+ participant_id: participant.id,+ },+ groups: {+ poll: participant.pollId,},});}),@@ -282,19 +284,26 @@ export const participants = router({}),);+ ctx.posthog?.groupIdentify({+ groupType: "poll",+ groupKey: pollId,+ properties: {+ participant_count: totalResponses,+ },+ });+// Track participant addition analytics- ctx.analytics.trackEvent({- type: "poll_response_submit",- userId: user.id,- pollId,+ ctx.posthog?.capture({+ distinctId: ctx.user.id,+ event: "poll_response_submit",properties: {- participantId: participant.id,- hasEmail: !!email,- totalResponses,- isCreator: ctx.user.isLegacyGuest- ? participant.poll.guestId === ctx.user.id- : participant.poll.userId === ctx.user.id,- isGuest: ctx.user.isGuest,+ participant_id: participant.id,+ participant_name: participant.name,+ has_email: !!email,+ total_responses: totalResponses,+ },+ groups: {+ poll: pollId,},});@@ -383,12 +392,11 @@ export const participants = router({});});- ctx.analytics.trackEvent({- type: "poll_response_update",- userId: ctx.user.id,- pollId,- properties: {- participantId,+ ctx.posthog?.capture({+ distinctId: ctx.user.id,+ event: "poll_response_update",+ groups: {+ poll: pollId,},});diff --git a/apps/web/src/trpc/routers/user.ts b/apps/web/src/trpc/routers/user.tsindex d375884ac..0ecdf894d 100644--- a/apps/web/src/trpc/routers/user.ts+++ b/apps/web/src/trpc/routers/user.ts@@ -1,5 +1,4 @@import { prisma } from "@rallly/database";-import { posthog } from "@rallly/posthog/server";import { absoluteUrl } from "@rallly/utils/absolute-url";import { TRPCError } from "@trpc/server";import { z } from "zod";@@ -140,7 +139,7 @@ export const user = router({},});- posthog?.capture({+ ctx.posthog?.capture({event: "account_email_change_request",distinctId: ctx.user.id,properties: {diff --git a/apps/web/src/trpc/trpc.ts b/apps/web/src/trpc/trpc.tsindex b57f44017..01c2c53cc 100644--- a/apps/web/src/trpc/trpc.ts+++ b/apps/web/src/trpc/trpc.ts@@ -1,12 +1,11 @@import { prisma } from "@rallly/database";-import { posthog } from "@rallly/posthog/server";import { initTRPC, TRPCError } from "@trpc/server";import { Ratelimit } from "@upstash/ratelimit";import { waitUntil } from "@vercel/functions";import { kv } from "@vercel/kv";import superjson from "superjson";import { getCurrentUserSpace } from "@/auth/data";-import { AnalyticsService } from "@/features/analytics/service";+import { PostHogClient } from "@/features/analytics/posthog";import { isQuickCreateEnabled } from "@/features/quick-create";import { isSelfHosted } from "@/utils/constants";import type { TRPCContext } from "./context";@@ -22,23 +21,21 @@ export const router = t.router;export const middleware = t.middleware;-export const procedureWithAnalytics = t.procedure.use(- async ({ next, type }) => {- const analytics = new AnalyticsService();+export const procedureWithAnalytics = t.procedure.use(async ({ next }) => {+ const posthog = PostHogClient();- const res = await next({- ctx: {- analytics,- },- });+ const res = await next({+ ctx: {+ posthog,+ },+ });- if (type === "mutation") {- waitUntil(analytics.shutdown());- }+ if (posthog) {+ waitUntil(posthog.shutdown());+ }- return res;- },-);+ return res;+});export const publicProcedure = procedureWithAnalytics;@@ -161,15 +158,6 @@ export const createRateLimitMiddleware = (const res = await ratelimit.limit(`${name}:${ctx.identifier}`);if (!res.success) {- posthog?.capture({- distinctId: ctx.user?.id ?? "system",- event: "ratelimit_exceeded",- properties: {- name,- requests,- duration,- },- });throw new TRPCError({code: "TOO_MANY_REQUESTS",message: "Too many requests",diff --git a/packages/posthog/src/server.ts b/packages/posthog/src/server.tsindex cb3789b26..2c049f868 100644--- a/packages/posthog/src/server.ts+++ b/packages/posthog/src/server.ts@@ -1,16 +1,3 @@import { PostHog } from "posthog-node";-function PostHogClient() {- if (!process.env.NEXT_PUBLIC_POSTHOG_API_KEY) return null;-- const posthogClient = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_API_KEY, {- host: process.env.NEXT_PUBLIC_POSTHOG_API_HOST,- flushAt: 1,- flushInterval: 0,- });- return posthogClient;-}-export { PostHog };--export const posthog = PostHogClient();