Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
♻️ Make posthog server client a singleton (#2272)
Luke Vella7ebc5aadb3c7
diff --git a/apps/web/src/app/api/better-auth/[...all]/route.ts b/apps/web/src/app/api/better-auth/[...all]/route.tsindex 8ef245888..d850ac461 100644--- a/apps/web/src/app/api/better-auth/[...all]/route.ts+++ b/apps/web/src/app/api/better-auth/[...all]/route.ts@@ -1,4 +1,8 @@import { toNextJsHandler } from "better-auth/next-js";import { authLib } from "@/lib/auth";+import { withPostHog } from "@/utils/posthog";-export const { POST, GET } = toNextJsHandler(authLib);+const { POST: authPost, GET: authGet } = toNextJsHandler(authLib);++export const POST = withPostHog(authPost);+export const GET = withPostHog(authGet);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 34da8599f..56d5d2ab0 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,7 +1,6 @@import type { Stripe } from "@rallly/billing";-import { waitUntil } from "@vercel/functions";import { env } from "@/env";-import { PostHogClient } from "@/features/analytics/posthog";+import { posthog } from "@/features/analytics/posthog";import { licenseCheckoutMetadataSchema } from "@/features/licensing/schema";import { licenseManager } from "@/features/licensing/server";import { getEmailClient } from "@/utils/emails";@@ -45,9 +44,7 @@ async function handleSelfHostedCheckoutSessionCompleted(seats,});- const posthog = PostHogClient();-- posthog?.capture({+ posthog()?.capture({distinctId: email,event: "license_purchase",properties: {@@ -60,10 +57,6 @@ 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 4171a8635..9fb7ce7d3 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,6 @@import type { Stripe } from "@rallly/billing";import { prisma } from "@rallly/database";-import { waitUntil } from "@vercel/functions";-import { PostHogClient } from "@/features/analytics/posthog";+import { posthog } from "@/features/analytics/posthog";import { subscriptionMetadataSchema } from "@/features/subscription/schema";import {getExpandedSubscription,@@ -91,9 +90,7 @@ export async function onCustomerSubscriptionCreated(event: Stripe.Event) {});});- const posthog = PostHogClient();-- posthog?.groupIdentify({+ posthog()?.groupIdentify({groupType: "space",groupKey: spaceId,properties: {@@ -102,7 +99,7 @@ export async function onCustomerSubscriptionCreated(event: Stripe.Event) {},});- posthog?.capture({+ posthog()?.capture({distinctId: userId,uuid: event.id,event: "subscription_create",@@ -116,8 +113,4 @@ 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 a433c9f54..8829a3bfa 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,7 @@import type { Stripe } from "@rallly/billing";import { stripe } from "@rallly/billing";import { prisma } from "@rallly/database";-import { waitUntil } from "@vercel/functions";-import { PostHogClient } from "@/features/analytics/posthog";+import { posthog } from "@/features/analytics/posthog";import { subscriptionMetadataSchema } from "@/features/subscription/schema";export async function onCustomerSubscriptionDeleted(event: Stripe.Event) {@@ -49,9 +48,7 @@ export async function onCustomerSubscriptionDeleted(event: Stripe.Event) {});});- const posthog = PostHogClient();-- posthog?.groupIdentify({+ posthog()?.groupIdentify({groupType: "space",groupKey: spaceId,properties: {@@ -59,7 +56,7 @@ export async function onCustomerSubscriptionDeleted(event: Stripe.Event) {},});- posthog?.capture({+ posthog()?.capture({distinctId: userId,event: "subscription_cancel",properties: {@@ -71,8 +68,4 @@ 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 bb3948f22..85c58c026 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,6 @@import type { Stripe } from "@rallly/billing";import { prisma } from "@rallly/database";-import { waitUntil } from "@vercel/functions";-import { PostHogClient } from "@/features/analytics/posthog";+import { posthog } from "@/features/analytics/posthog";import { subscriptionMetadataSchema } from "@/features/subscription/schema";import {getExpandedSubscription,@@ -89,9 +88,7 @@ export async function onCustomerSubscriptionUpdated(event: Stripe.Event) {});});- const posthog = PostHogClient();-- posthog?.groupIdentify({+ posthog()?.groupIdentify({groupType: "space",groupKey: spaceId,properties: {@@ -100,7 +97,7 @@ export async function onCustomerSubscriptionUpdated(event: Stripe.Event) {},});- posthog?.capture({+ posthog()?.capture({distinctId: userId,uuid: event.id,event: "subscription_update",@@ -115,8 +112,4 @@ export async function onCustomerSubscriptionUpdated(event: Stripe.Event) {space: spaceId,},});-- if (posthog) {- waitUntil(posthog.shutdown());- }}diff --git a/apps/web/src/app/api/stripe/webhook/handlers/index.ts b/apps/web/src/app/api/stripe/webhook/handlers/index.tsindex 82b401888..0bc44fd62 100644--- a/apps/web/src/app/api/stripe/webhook/handlers/index.ts+++ b/apps/web/src/app/api/stripe/webhook/handlers/index.ts@@ -12,7 +12,11 @@ import {onPaymentMethodUpdated,} from "./payment-method";-export function getEventHandler(eventType: Stripe.Event["type"]) {+type WebhookHandler = (event: Stripe.Event) => Promise<void>;++export function getEventHandler(+ eventType: Stripe.Event["type"],+): WebhookHandler | null {switch (eventType) {case "checkout.session.completed":return onCheckoutSessionCompleted;diff --git a/apps/web/src/app/api/stripe/webhook/route.ts b/apps/web/src/app/api/stripe/webhook/route.tsindex 8724ef9be..812ee17bc 100644--- a/apps/web/src/app/api/stripe/webhook/route.ts+++ b/apps/web/src/app/api/stripe/webhook/route.ts@@ -4,9 +4,10 @@ import * as Sentry from "@sentry/nextjs";import type { NextRequest } from "next/server";import { NextResponse } from "next/server";import { isSelfHosted } from "@/utils/constants";+import { withPostHog } from "@/utils/posthog";import { getEventHandler } from "./handlers";-export const POST = async (request: NextRequest) => {+const handler = async (request: NextRequest) => {if (isSelfHosted) {return NextResponse.json({ error: "This endpoint is not available on self-hosted instances" },@@ -62,3 +63,5 @@ export const POST = async (request: NextRequest) => {);}};++export const POST = withPostHog(handler);diff --git a/apps/web/src/app/api/trpc/[trpc]/route.ts b/apps/web/src/app/api/trpc/[trpc]/route.tsindex e594e24b9..30039e346 100644--- a/apps/web/src/app/api/trpc/[trpc]/route.ts+++ b/apps/web/src/app/api/trpc/[trpc]/route.ts@@ -4,11 +4,11 @@ import { fetchRequestHandler } from "@trpc/server/adapters/fetch";import { getHTTPStatusCodeFromError } from "@trpc/server/http";import { ipAddress } from "@vercel/functions";import type { NextRequest } from "next/server";-import { getUserSession } from "@/features/user/data";import { getLocaleFromRequest } from "@/lib/locale/server";import type { TRPCContext } from "@/trpc/context";import { appRouter } from "@/trpc/routers";+import { withPostHog } from "@/utils/posthog";const handler = async (req: NextRequest) => {const { user } = await getUserSession();@@ -63,7 +63,9 @@ const handler = async (req: NextRequest) => {}},});+event.statusCode = response.status;+return response;} catch (error) {event.statusCode = 500;@@ -84,4 +86,6 @@ const handler = async (req: NextRequest) => {}};-export { handler as GET, handler as POST };+const handlerWithPostHog = withPostHog(handler);++export { handlerWithPostHog as GET, handlerWithPostHog as POST };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 a9aff4a37..caba38b94 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@@ -2,11 +2,11 @@ import { stripe } from "@rallly/billing";import { prisma } from "@rallly/database";import { absoluteUrl } from "@rallly/utils/absolute-url";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 { posthog } from "@/features/analytics/posthog";import { getSession } from "@/lib/auth";+import { withPostHog } from "@/utils/posthog";import { decryptToken } from "@/utils/session";type EmailChangePayload = {@@ -14,7 +14,7 @@ type EmailChangePayload = {toEmail: string;};-export const GET = async (request: NextRequest) => {+const handler = async (request: NextRequest) => {const token = request.nextUrl.searchParams.get("token");if (!token) {@@ -64,9 +64,7 @@ export const GET = async (request: NextRequest) => {Sentry.captureException(error);}- const posthog = PostHogClient();-- posthog?.capture({+ posthog()?.capture({event: "account_email_change_complete",distinctId: session.user.id,properties: {@@ -76,11 +74,9 @@ export const GET = async (request: NextRequest) => {},});- if (posthog) {- waitUntil(posthog.shutdown());- }-return NextResponse.redirect(absoluteUrl("/settings/profile?emailChanged=true"),);};++export const GET = withPostHog(handler);diff --git a/apps/web/src/auth/helpers/merge-user.ts b/apps/web/src/auth/helpers/merge-user.tsindex f13bd04b5..829bc0e85 100644--- a/apps/web/src/auth/helpers/merge-user.ts+++ b/apps/web/src/auth/helpers/merge-user.ts@@ -1,8 +1,7 @@import { prisma } from "@rallly/database";import { createLogger } from "@rallly/logger";import * as Sentry from "@sentry/nextjs";-import { waitUntil } from "@vercel/functions";-import { PostHogClient } from "@/features/analytics/posthog";+import { posthog } from "@/features/analytics/posthog";const logger = createLogger("auth/merge-user");@@ -70,17 +69,12 @@ export const linkAnonymousUser = async (]);});- const posthog = PostHogClient();// Merge user identities in PostHog- posthog?.capture({+ posthog()?.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.tsindex 920167c86..e47bafc8d 100644--- a/apps/web/src/features/analytics/posthog.ts+++ b/apps/web/src/features/analytics/posthog.ts@@ -1,12 +1,16 @@import { PostHog } from "@rallly/posthog/server";import { env } from "@/env";-export function PostHogClient() {- if (!env.NEXT_PUBLIC_POSTHOG_API_KEY) return null;+let instance: PostHog | undefined;- return new PostHog(env.NEXT_PUBLIC_POSTHOG_API_KEY, {- host: env.NEXT_PUBLIC_POSTHOG_API_HOST,- flushAt: 20,- flushInterval: 10000,- });+export function posthog() {+ if (!instance && env.NEXT_PUBLIC_POSTHOG_API_KEY) {+ instance = new PostHog(env.NEXT_PUBLIC_POSTHOG_API_KEY, {+ host: env.NEXT_PUBLIC_POSTHOG_API_HOST,+ flushAt: 20,+ flushInterval: 10000,+ });+ }++ return instance;}diff --git a/apps/web/src/features/developer/data.ts b/apps/web/src/features/developer/data.tsindex 631319eac..7300540a3 100644--- a/apps/web/src/features/developer/data.ts+++ b/apps/web/src/features/developer/data.ts@@ -1,4 +1,4 @@-import { PostHogClient } from "@/features/analytics/posthog";+import { posthog } from "@/features/analytics/posthog";import type { SpaceTier } from "@/features/space/schema";import { isSelfHosted } from "@/utils/constants";@@ -33,8 +33,7 @@ export async function isApiAccessEnabled(}// Check PostHog feature flag- const posthog = PostHogClient();- const isFeatureFlagEnabled = await posthog?.isFeatureEnabled(+ const isFeatureFlagEnabled = await posthog()?.isFeatureEnabled("developer-tools",user.id,);diff --git a/apps/web/src/lib/auth.ts b/apps/web/src/lib/auth.tsindex 4a5f94aff..fd611c854 100644--- a/apps/web/src/lib/auth.ts+++ b/apps/web/src/lib/auth.ts@@ -21,7 +21,7 @@ import { isEmailBlocked } from "@/auth/helpers/is-email-blocked";import { linkAnonymousUser } from "@/auth/helpers/merge-user";import { isTemporaryEmail } from "@/auth/helpers/temp-email-domains";import { env } from "@/env";-import { PostHogClient } from "@/features/analytics/posthog";+import { posthog } from "@/features/analytics/posthog";import { createSpace } from "@/features/space/mutations";import { getTranslation } from "@/i18n/server";import { getLocale } from "@/i18n/server/get-locale";@@ -104,14 +104,10 @@ export const authLib = betterAuth({});},onPasswordReset: async ({ user }) => {- const posthog = PostHogClient();- posthog?.capture({+ posthog()?.capture({distinctId: user.id,event: "password_reset",});- if (posthog) {- waitUntil(posthog.shutdown());- }},},emailVerification: {@@ -281,8 +277,6 @@ export const authLib = betterAuth({},});- const posthog = PostHogClient();-if (existingUser) {// create a space for the userconst space = await createSpace({@@ -290,7 +284,7 @@ export const authLib = betterAuth({ownerId: user.id,});- posthog?.groupIdentify({+ posthog()?.groupIdentify({groupType: "space",groupKey: space.id,properties: {@@ -302,7 +296,7 @@ export const authLib = betterAuth({});}- posthog?.capture({+ posthog()?.capture({distinctId: user.id,event: "register",properties: {@@ -316,10 +310,6 @@ export const authLib = betterAuth({},},});-- if (posthog) {- waitUntil(posthog.shutdown());- }},},},@@ -334,17 +324,11 @@ 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({+ posthog()?.capture({distinctId: session.userId,event: "login",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 35d87fd47..e64b2c538 100644--- a/apps/web/src/lib/safe-action/server.ts+++ b/apps/web/src/lib/safe-action/server.ts@@ -5,7 +5,7 @@ import { waitUntil } from "@vercel/functions";import { createMiddleware, createSafeActionClient } from "next-safe-action";import * as z from "zod";import { getCurrentUser, getCurrentUserSpace } from "@/auth/data";-import { PostHogClient } from "@/features/analytics/posthog";+import { posthog } from "@/features/analytics/posthog";import { defineAbilityForSpace } from "@/features/space/ability";import { defineAbilityForMember } from "@/features/space/member/ability";import { defineAbilityFor } from "@/features/user/ability";@@ -14,16 +14,11 @@ import type { Duration } from "@/lib/rate-limit";import { createRatelimit } from "@/lib/rate-limit";export const posthogMiddleware = createMiddleware().define(async ({ next }) => {- const posthog = PostHogClient();+ const result = await next();- const result = await next({- ctx: {- posthog,- },- });-- if (posthog) {- waitUntil(posthog.shutdown());+ const ph = posthog();+ if (ph) {+ waitUntil(ph.flush());}return result;diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.tsindex d83a746ad..af4721ed8 100644--- a/apps/web/src/trpc/routers/polls.ts+++ b/apps/web/src/trpc/routers/polls.ts@@ -4,6 +4,7 @@ import { absoluteUrl, shortUrl } from "@rallly/utils/absolute-url";import { nanoid } from "@rallly/utils/nanoid";import { TRPCError } from "@trpc/server";import * as z from "zod";+import { posthog } from "@/features/analytics/posthog";import { moderateContent } from "@/features/moderation";import { getPolls } from "@/features/poll/data";import { canUserManagePoll } from "@/features/poll/helpers";@@ -149,7 +150,7 @@ export const polls = router({});if (moderation.verdict !== "safe") {- ctx.posthog?.capture({+ posthog()?.capture({distinctId: ctx.user.id,event: "flagged_content",properties: {@@ -241,7 +242,7 @@ export const polls = router({}}- ctx.posthog?.groupIdentify({+ posthog()?.groupIdentify({groupType: "poll",groupKey: poll.id,properties: {@@ -259,7 +260,7 @@ export const polls = router({},});- ctx.posthog?.capture({+ posthog()?.capture({event: "poll_create",distinctId: ctx.user.id,properties: {@@ -326,7 +327,7 @@ export const polls = router({});if (moderation.verdict !== "safe") {- ctx.posthog?.capture({+ posthog()?.capture({distinctId: ctx.user.id,event: "flagged_content",properties: {@@ -445,7 +446,7 @@ export const polls = router({input.requireParticipantEmail !== undefined;if (hasDetailsUpdate) {- ctx.posthog?.capture({+ posthog()?.capture({event: "poll_update_details",distinctId: ctx.user.id,properties: {@@ -461,7 +462,7 @@ export const polls = router({}if (hasOptionsUpdate) {- ctx.posthog?.capture({+ posthog()?.capture({event: "poll_update_options",distinctId: ctx.user.id,properties: {@@ -474,7 +475,7 @@ export const polls = router({}if (hasSettingsUpdate) {- ctx.posthog?.capture({+ posthog()?.capture({event: "poll_update_settings",distinctId: ctx.user.id,properties: {@@ -514,7 +515,7 @@ export const polls = router({});// Track poll deletion analytics- ctx.posthog?.capture({+ posthog()?.capture({event: "poll_delete",distinctId: ctx.user.id,groups: {@@ -543,7 +544,7 @@ export const polls = router({data: { muted: input.muted },});- ctx.posthog?.groupIdentify({+ posthog()?.groupIdentify({groupType: "poll",groupKey: input.pollId,properties: {@@ -551,7 +552,7 @@ export const polls = router({},});- ctx.posthog?.capture({+ posthog()?.capture({event: "poll_notification_toggle",distinctId: ctx.user.id,properties: {@@ -978,7 +979,7 @@ export const polls = router({});}- ctx.posthog?.capture({+ posthog()?.capture({event: "poll_schedule",distinctId: ctx.user.id,properties: {@@ -1027,7 +1028,7 @@ export const polls = router({}});- ctx.posthog?.capture({+ posthog()?.capture({event: "poll_reopen",distinctId: ctx.user.id,groups: {@@ -1061,7 +1062,7 @@ export const polls = router({},});- ctx.posthog?.capture({+ posthog()?.capture({event: "poll_close",distinctId: ctx.user.id,groups: {diff --git a/apps/web/src/trpc/routers/polls/comments.ts b/apps/web/src/trpc/routers/polls/comments.tsindex 2231d382d..affe765ac 100644--- a/apps/web/src/trpc/routers/polls/comments.ts+++ b/apps/web/src/trpc/routers/polls/comments.ts@@ -3,6 +3,7 @@ import { createLogger } from "@rallly/logger";import { absoluteUrl } from "@rallly/utils/absolute-url";import { TRPCError } from "@trpc/server";import * as z from "zod";+import { posthog } from "@/features/analytics/posthog";import { getNotificationRecipient } from "@/features/notifications/queries";import { hasPollAdminAccess } from "@/features/poll/query";import { getEmailClient } from "@/utils/emails";@@ -156,7 +157,7 @@ export const comments = router({}// Track comment addition analytics- ctx.posthog?.capture({+ posthog()?.capture({distinctId: ctx.user.id,event: "poll_comment_add",properties: {@@ -208,7 +209,7 @@ export const comments = router({// Track comment deletion analyticsif (comment) {- ctx.posthog?.capture({+ posthog()?.capture({distinctId: userId,event: "poll_comment_delete",groups: {diff --git a/apps/web/src/trpc/routers/polls/participants.ts b/apps/web/src/trpc/routers/polls/participants.tsindex 373843430..42f017b56 100644--- a/apps/web/src/trpc/routers/polls/participants.ts+++ b/apps/web/src/trpc/routers/polls/participants.ts@@ -4,6 +4,7 @@ import { absoluteUrl } from "@rallly/utils/absolute-url";import { TRPCError } from "@trpc/server";import { waitUntil } from "@vercel/functions";import * as z from "zod";+import { posthog } from "@/features/analytics/posthog";import { getNotificationRecipient } from "@/features/notifications/queries";import { hasPollAdminAccess } from "@/features/poll/query";import { getEmailClient } from "@/utils/emails";@@ -169,7 +170,7 @@ export const participants = router({},});- ctx.posthog?.capture({+ posthog()?.capture({distinctId: userId,event: "poll_response_delete",properties: {@@ -286,7 +287,7 @@ export const participants = router({}),);- ctx.posthog?.groupIdentify({+ posthog()?.groupIdentify({groupType: "poll",groupKey: pollId,properties: {@@ -295,7 +296,7 @@ export const participants = router({});// Track participant addition analytics- ctx.posthog?.capture({+ posthog()?.capture({distinctId: ctx.user.id,event: "poll_response_submit",properties: {@@ -403,7 +404,7 @@ export const participants = router({});});- ctx.posthog?.capture({+ posthog()?.capture({distinctId: userId,event: "poll_response_update",groups: {diff --git a/apps/web/src/trpc/routers/spaces.ts b/apps/web/src/trpc/routers/spaces.tsindex ca2232e65..d5f224f87 100644--- a/apps/web/src/trpc/routers/spaces.ts+++ b/apps/web/src/trpc/routers/spaces.ts@@ -5,6 +5,7 @@ import { absoluteUrl } from "@rallly/utils/absolute-url";import { TRPCError } from "@trpc/server";import { waitUntil } from "@vercel/functions";import * as z from "zod";+import { posthog } from "@/features/analytics/posthog";import { defineAbilityForSpace } from "@/features/space/ability";import {createSpaceDTO,@@ -174,7 +175,7 @@ export const spaces = router({spaceId: input.spaceId,});- ctx.posthog?.capture({+ posthog()?.capture({distinctId: ctx.user.id,event: "space_set_active",properties: {@@ -195,7 +196,7 @@ export const spaces = router({ownerId: ctx.user.id,});- ctx.posthog?.groupIdentify({+ posthog()?.groupIdentify({groupType: "space",groupKey: space.id,properties: {@@ -206,7 +207,7 @@ export const spaces = router({},});- ctx.posthog?.capture({+ posthog()?.capture({distinctId: ctx.user.id,event: "space_create",properties: {@@ -249,7 +250,7 @@ export const spaces = router({where: { id: ctx.space.id },});- ctx.posthog?.capture({+ posthog()?.capture({distinctId: ctx.user.id,event: "space_delete",properties: {@@ -281,7 +282,7 @@ export const spaces = router({data: { name: input.name },});- ctx.posthog?.capture({+ posthog()?.capture({distinctId: ctx.user.id,event: "space_update",properties: {@@ -412,7 +413,7 @@ export const spaces = router({};}- ctx.posthog?.capture({+ posthog()?.capture({distinctId: ctx.user.id,event: "space_member_invite",properties: {@@ -486,7 +487,7 @@ export const spaces = router({logger.warn({ error }, "Failed to update user's active space");}- ctx.posthog?.capture({+ posthog()?.capture({distinctId: ctx.user.id,event: "space_member_join",properties: {@@ -530,7 +531,7 @@ export const spaces = router({where: { spaceId: member.spaceId },});- ctx.posthog?.capture({+ posthog()?.capture({distinctId: ctx.user.id,event: "space_member_remove",properties: {@@ -664,7 +665,7 @@ export const spaces = router({where: { spaceId: ctx.space.id },});- ctx.posthog?.capture({+ posthog()?.capture({distinctId: ctx.user.id,event: "space_member_leave",properties: {@@ -743,7 +744,7 @@ export const spaces = router({where: { spaceId: input.spaceId },});- ctx.posthog?.capture({+ posthog()?.capture({distinctId: ctx.user.id,event: "space_member_leave",properties: {diff --git a/apps/web/src/trpc/routers/user.ts b/apps/web/src/trpc/routers/user.tsindex 24cf0a43c..c9f1ab054 100644--- a/apps/web/src/trpc/routers/user.ts+++ b/apps/web/src/trpc/routers/user.ts@@ -3,6 +3,7 @@ import { prisma } from "@rallly/database";import { absoluteUrl } from "@rallly/utils/absolute-url";import { TRPCError } from "@trpc/server";import * as z from "zod";+import { posthog } from "@/features/analytics/posthog";import { feedbackSchema } from "@/features/feedback/schema";import { defaultNotificationPreferences } from "@/features/notifications/constants";import { getNotificationPreferences } from "@/features/notifications/queries";@@ -127,7 +128,7 @@ export const user = router({},});- ctx.posthog?.capture({+ posthog()?.capture({event: "account_email_change_request",distinctId: ctx.user.id,properties: {@@ -273,7 +274,7 @@ export const user = router({},});- ctx.posthog?.capture({+ posthog()?.capture({event: "notification_preference_update",distinctId: ctx.user.id,properties: {@@ -301,7 +302,7 @@ export const user = router({text: `User: ${ctx.user.name} (${ctx.user.email})\n\n${input.content}`,});- ctx.posthog?.capture({+ posthog()?.capture({event: "feedback_send",distinctId: ctx.user.id,});diff --git a/apps/web/src/trpc/trpc.ts b/apps/web/src/trpc/trpc.tsindex eec4793f5..d14f2384a 100644--- a/apps/web/src/trpc/trpc.ts+++ b/apps/web/src/trpc/trpc.ts@@ -1,7 +1,5 @@import { initTRPC, TRPCError } from "@trpc/server";-import { waitUntil } from "@vercel/functions";import superjson from "superjson";-import { PostHogClient } from "@/features/analytics/posthog";import { isQuickCreateEnabled } from "@/features/quick-create";import { getActiveSpaceForUser } from "@/features/space/data";import { AppError } from "@/lib/errors";@@ -27,25 +25,9 @@ export const router = t.router;export const middleware = t.middleware;-export const procedureWithAnalytics = t.procedure.use(async ({ next }) => {- const posthog = PostHogClient();+export const publicProcedure = t.procedure;- const res = await next({- ctx: {- posthog,- },- });-- if (posthog) {- waitUntil(posthog.shutdown());- }-- return res;-});--export const publicProcedure = procedureWithAnalytics;--export const possiblyPublicProcedure = procedureWithAnalytics.use(+export const possiblyPublicProcedure = publicProcedure.use(middleware(async ({ ctx, next }) => {// These procedures are public if Quick Create is enabledconst isGuest = !ctx.user || ctx.user.isGuest;@@ -83,22 +65,20 @@ export const requireUserMiddleware = middleware(async ({ ctx, next }) => {});});-export const privateProcedure = procedureWithAnalytics.use(- async ({ ctx, next }) => {- if (!ctx.user || ctx.user.isGuest !== false) {- throw new TRPCError({- code: "UNAUTHORIZED",- message: "Login is required",- });- }-- return next({- ctx: {- user: ctx.user,- },+export const privateProcedure = publicProcedure.use(async ({ ctx, next }) => {+ if (!ctx.user || ctx.user.isGuest !== false) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "Login is required",});- },-);+ }++ return next({+ ctx: {+ user: ctx.user,+ },+ });+});export const adminProcedure = privateProcedure.use(async ({ ctx, next }) => {if (ctx.user.role !== "admin") {diff --git a/apps/web/src/utils/posthog.ts b/apps/web/src/utils/posthog.tsnew file mode 100644index 000000000..5b3d11394--- /dev/null+++ b/apps/web/src/utils/posthog.ts@@ -0,0 +1,18 @@+import { waitUntil } from "@vercel/functions";+import type { NextRequest } from "next/server";+import { posthog } from "@/features/analytics/posthog";++export function withPostHog(+ handler: (req: NextRequest) => Promise<Response>,+): (req: NextRequest) => Promise<Response> {+ return async (req: NextRequest) => {+ try {+ return await handler(req);+ } finally {+ const ph = posthog();+ if (ph) {+ waitUntil(ph.flush());+ }+ }+ };+}