Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

🐛 Flush PostHog events after every server action (#3165)

Luke Vellaa2f2bd3a4d92
diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/actions.ts b/apps/web/src/app/[locale]/(space)/settings/profile/actions.ts
index 02ff9e98b..b0f636f80 100644
--- a/apps/web/src/app/[locale]/(space)/settings/profile/actions.ts
+++ b/apps/web/src/app/[locale]/(space)/settings/profile/actions.ts
@@ -17,12 +17,7 @@ import { getLocale } from "@/i18n/server/get-locale";
import { isSelfHosted } from "@/lib/constants";
import { formatDateTime } from "@/lib/datetime/format";
import { AppError } from "@/lib/errors/app-error";
-import {
- deletePostHogPerson,
- flushPostHog,
- track,
- trackSystemEvent,
-} from "@/lib/posthog";
+import { deletePostHogPerson, track, trackSystemEvent } from "@/lib/posthog";
import {
authActionClient,
createRateLimitMiddleware,
@@ -118,7 +113,6 @@ export const deleteAccountAction = authActionClient
// Personless by design — the person this event is about was just erased.
trackSystemEvent({ event: "account_deletion_complete" });
- after(() => flushPostHog());
});
export const cancelAccountDeletionAction = authActionClient
diff --git a/apps/web/src/lib/safe-action/server.ts b/apps/web/src/lib/safe-action/server.ts
index 51ca4b935..30111fdfd 100644
--- a/apps/web/src/lib/safe-action/server.ts
+++ b/apps/web/src/lib/safe-action/server.ts
@@ -2,6 +2,7 @@ import "server-only";
import * as Sentry from "@sentry/nextjs";
import { APIError } from "better-auth/api";
+import { after } from "next/server";
import { createMiddleware, createSafeActionClient } from "next-safe-action";
import * as z from "zod";
import { defineAbilityFor } from "@/features/user/ability";
@@ -10,6 +11,7 @@ import { signOut } from "@/lib/auth";
import { AppError } from "@/lib/errors/app-error";
import { InvalidSessionError } from "@/lib/errors/invalid-session-error";
import { assertAppAvailable } from "@/lib/maintenance-server";
+import { flushPostHog } from "@/lib/posthog";
import type { Duration } from "@/lib/rate-limit";
import { createRatelimit } from "@/lib/rate-limit";
@@ -95,10 +97,22 @@ export const actionClient = createSafeActionClient({
return "INTERNAL_SERVER_ERROR" as const;
},
-}).use(async ({ next }) => {
- await assertAppAvailable();
- return next();
-});
+})
+ // The PostHog client only enqueues; a serverless function freezes once the
+ // action response is sent, so the buffer must be flushed here. Route
+ // handlers get the same through withPostHog. Runs in finally so a failed
+ // action's events still flush.
+ .use(async ({ next }) => {
+ try {
+ return await next();
+ } finally {
+ after(() => flushPostHog());
+ }
+ })
+ .use(async ({ next }) => {
+ await assertAppAvailable();
+ return next();
+ });
export const authActionClient = actionClient.use(async ({ next }) => {
const user = await getCurrentUser();