Skip to content

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

📈 Conditionally initialize posthog (#586)

Luke Vellad9061d45fa3e
diff --git a/apps/web/package.json b/apps/web/package.json
index 9c543b9cb..b779c07e4 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -46,7 +46,7 @@
"next-i18next": "^13.0.3",
"next-seo": "^5.15.0",
"postcss": "^8.4.21",
- "posthog-js": "^1.42.3",
+ "posthog-js": "^1.51.3",
"react": "^18.2.0",
"react-big-calendar": "^1.5.0",
"react-dom": "^18.2.0",
diff --git a/apps/web/src/components/admin-control.tsx b/apps/web/src/components/admin-control.tsx
index 9ddf4fe11..3c055168c 100644
--- a/apps/web/src/components/admin-control.tsx
+++ b/apps/web/src/components/admin-control.tsx
@@ -1,12 +1,12 @@
import { AnimatePresence, m } from "framer-motion";
import { useRouter } from "next/router";
import { useTranslation } from "next-i18next";
-import posthog from "posthog-js";
import React from "react";
import toast from "react-hot-toast";
import { Button } from "@/components/button";
import Share from "@/components/icons/share.svg";
+import { usePostHog } from "@/utils/posthog";
import { useParticipants } from "./participants-provider";
import ManagePoll from "./poll/manage-poll";
@@ -22,6 +22,7 @@ export const AdminControls = (props: { children?: React.ReactNode }) => {
const router = useRouter();
const { mutate: updatePollMutation } = useUpdatePollMutation();
+ const posthog = usePostHog();
React.useEffect(() => {
if (router.query.unsubscribe) {
@@ -30,7 +31,7 @@ export const AdminControls = (props: { children?: React.ReactNode }) => {
{
onSuccess: () => {
toast.success(t("notificationsDisabled"));
- posthog.capture("unsubscribed from notifications");
+ posthog?.capture("unsubscribed from notifications");
},
},
);
@@ -38,7 +39,7 @@ export const AdminControls = (props: { children?: React.ReactNode }) => {
shallow: true,
});
}
- }, [urlId, router, updatePollMutation, t]);
+ }, [urlId, router, updatePollMutation, t, posthog]);
const { participants } = useParticipants();
diff --git a/apps/web/src/components/auth/login-form.tsx b/apps/web/src/components/auth/login-form.tsx
index a7d395786..c5a9561e6 100644
--- a/apps/web/src/components/auth/login-form.tsx
+++ b/apps/web/src/components/auth/login-form.tsx
@@ -1,9 +1,10 @@
import Link from "next/link";
import { Trans, useTranslation } from "next-i18next";
-import posthog from "posthog-js";
import React from "react";
import { useForm } from "react-hook-form";
+import { usePostHog } from "@/utils/posthog";
+
import { requiredString, validEmail } from "../../utils/form-validation";
import { trpc } from "../../utils/trpc";
import { Button } from "../button";
@@ -139,7 +140,7 @@ export const RegisterForm: React.FunctionComponent<{
const authenticateRegistration =
trpc.auth.authenticateRegistration.useMutation();
const [token, setToken] = React.useState<string>();
-
+ const posthog = usePostHog();
if (token) {
return (
<VerifyCode
@@ -154,11 +155,11 @@ export const RegisterForm: React.FunctionComponent<{
}
onRegistered();
- posthog.identify(res.user.id, {
+ posthog?.identify(res.user.id, {
email: res.user.email,
name: res.user.name,
});
- posthog.capture("register");
+ posthog?.capture("register");
}}
onResend={async () => {
const values = getValues();
@@ -285,7 +286,7 @@ export const LoginForm: React.FunctionComponent<{
const authenticateLogin = trpc.auth.authenticateLogin.useMutation();
const [token, setToken] = React.useState<string>();
-
+ const posthog = usePostHog();
if (token) {
return (
<VerifyCode
@@ -299,11 +300,11 @@ export const LoginForm: React.FunctionComponent<{
throw new Error("Failed to authenticate user");
} else {
onAuthenticated();
- posthog.identify(res.user.id, {
+ posthog?.identify(res.user.id, {
email: res.user.email,
name: res.user.name,
});
- posthog.capture("login");
+ posthog?.capture("login");
}
}}
onResend={async () => {
diff --git a/apps/web/src/components/create-poll.tsx b/apps/web/src/components/create-poll.tsx
index 7ef501dfe..8f5aef1fe 100644
--- a/apps/web/src/components/create-poll.tsx
+++ b/apps/web/src/components/create-poll.tsx
@@ -1,9 +1,10 @@
import { useRouter } from "next/router";
import { useTranslation } from "next-i18next";
-import posthog from "posthog-js";
import React from "react";
import { useSessionStorage } from "react-use";
+import { usePostHog } from "@/utils/posthog";
+
import { encodeDateOption } from "../utils/date-time-utils";
import { trpc } from "../utils/trpc";
import { Button } from "./button";
@@ -89,10 +90,12 @@ const Page: React.FunctionComponent<CreatePollPageProps> = ({
const [isRedirecting, setIsRedirecting] = React.useState(false);
+ const posthog = usePostHog();
+
const createPoll = trpc.polls.create.useMutation({
onSuccess: (res) => {
setIsRedirecting(true);
- posthog.capture("created poll", {
+ posthog?.capture("created poll", {
pollId: res.id,
numberOfOptions: formData.options?.options?.length,
optionsView: formData?.options?.view,
diff --git a/apps/web/src/components/discussion/discussion.tsx b/apps/web/src/components/discussion/discussion.tsx
index d8e944ce1..4fab945f3 100644
--- a/apps/web/src/components/discussion/discussion.tsx
+++ b/apps/web/src/components/discussion/discussion.tsx
@@ -1,9 +1,10 @@
import clsx from "clsx";
import { useTranslation } from "next-i18next";
-import posthog from "posthog-js";
import * as React from "react";
import { Controller, useForm } from "react-hook-form";
+import { usePostHog } from "@/utils/posthog";
+
import { useDayjs } from "../../utils/dayjs";
import { requiredString } from "../../utils/form-validation";
import { trpc } from "../../utils/trpc";
@@ -38,10 +39,11 @@ const Discussion: React.FunctionComponent = () => {
trpc: {},
},
);
+ const posthog = usePostHog();
const addComment = trpc.polls.comments.add.useMutation({
onSuccess: (newComment) => {
- posthog.capture("created comment");
+ posthog?.capture("created comment");
queryClient.polls.comments.list.setData(
{ pollId },
@@ -62,7 +64,7 @@ const Discussion: React.FunctionComponent = () => {
);
},
onSuccess: () => {
- posthog.capture("deleted comment");
+ posthog?.capture("deleted comment");
},
});
diff --git a/apps/web/src/components/participant-dropdown.tsx b/apps/web/src/components/participant-dropdown.tsx
index eabc7b84b..a1b5634d7 100644
--- a/apps/web/src/components/participant-dropdown.tsx
+++ b/apps/web/src/components/participant-dropdown.tsx
@@ -15,6 +15,7 @@ import { useModalState } from "@/components/modal/use-modal";
import { useDeleteParticipantModal } from "@/components/poll/use-delete-participant-modal";
import { TextInput } from "@/components/text-input";
import { useFormValidation } from "@/utils/form-validation";
+import { usePostHog } from "@/utils/posthog";
import { trpc } from "@/utils/trpc";
import { Participant } from ".prisma/client";
@@ -92,9 +93,10 @@ const ChangeNameModal = (props: {
participantId: string;
onDone: () => void;
}) => {
+ const posthog = usePostHog();
const changeName = trpc.polls.participants.rename.useMutation({
onSuccess: (_, { participantId, newName }) => {
- posthog.capture("changed name", {
+ posthog?.capture("changed name", {
participantId,
oldName: props.oldName,
newName,
diff --git a/apps/web/src/components/poll/manage-poll/delete-poll-form.tsx b/apps/web/src/components/poll/manage-poll/delete-poll-form.tsx
index db9b00969..3f57c1dc7 100644
--- a/apps/web/src/components/poll/manage-poll/delete-poll-form.tsx
+++ b/apps/web/src/components/poll/manage-poll/delete-poll-form.tsx
@@ -1,11 +1,11 @@
import clsx from "clsx";
import { Trans, useTranslation } from "next-i18next";
-import posthog from "posthog-js";
import * as React from "react";
import { useForm } from "react-hook-form";
import { Button } from "@/components/button";
import Exclamation from "@/components/icons/exclamation.svg";
+import { usePostHog } from "@/utils/posthog";
import { trpc } from "../../../utils/trpc";
@@ -22,9 +22,10 @@ export const DeletePollForm: React.FunctionComponent<{
const confirmationText = watch("confirmation");
const canDelete = confirmationText === confirmText;
+ const posthog = usePostHog();
const deletePoll = trpc.polls.delete.useMutation({
onSuccess: () => {
- posthog.capture("deleted poll");
+ posthog?.capture("deleted poll");
},
});
diff --git a/apps/web/src/components/poll/mutations.ts b/apps/web/src/components/poll/mutations.ts
index 866efe4c2..0b74e582a 100644
--- a/apps/web/src/components/poll/mutations.ts
+++ b/apps/web/src/components/poll/mutations.ts
@@ -1,4 +1,4 @@
-import posthog from "posthog-js";
+import { usePostHog } from "@/utils/posthog";
import { trpc } from "../../utils/trpc";
import { ParticipantForm } from "./types";
@@ -14,9 +14,10 @@ export const normalizeVotes = (
};
export const useAddParticipantMutation = () => {
+ const posthog = usePostHog();
return trpc.polls.participants.add.useMutation({
onSuccess: (_, { pollId, name, email }) => {
- posthog.capture("add participant", {
+ posthog?.capture("add participant", {
pollId,
name,
email,
@@ -27,9 +28,10 @@ export const useAddParticipantMutation = () => {
export const useUpdateParticipantMutation = () => {
const queryClient = trpc.useContext();
+ const posthog = usePostHog();
return trpc.polls.participants.update.useMutation({
onSuccess: (participant) => {
- posthog.capture("update participant", {
+ posthog?.capture("update participant", {
name: participant.name,
});
queryClient.polls.participants.list.setData(
@@ -54,6 +56,7 @@ export const useUpdateParticipantMutation = () => {
export const useDeleteParticipantMutation = () => {
const queryClient = trpc.useContext();
+ const posthog = usePostHog();
return trpc.polls.participants.delete.useMutation({
onMutate: ({ participantId, pollId }) => {
queryClient.polls.participants.list.setData(
@@ -64,7 +67,7 @@ export const useDeleteParticipantMutation = () => {
);
},
onSuccess: (_, { pollId, participantId }) => {
- posthog.capture("remove participant", {
+ posthog?.capture("remove participant", {
pollId,
participantId,
});
@@ -74,10 +77,11 @@ export const useDeleteParticipantMutation = () => {
export const useUpdatePollMutation = () => {
const queryClient = trpc.useContext();
+ const posthog = usePostHog();
return trpc.polls.update.useMutation({
onSuccess: (data) => {
queryClient.polls.invalidate();
- posthog.capture("updated poll", {
+ posthog?.capture("updated poll", {
id: data.id,
});
},
diff --git a/apps/web/src/components/user-provider.tsx b/apps/web/src/components/user-provider.tsx
index 76dd00a30..424ae70ec 100644
--- a/apps/web/src/components/user-provider.tsx
+++ b/apps/web/src/components/user-provider.tsx
@@ -1,9 +1,8 @@
import { useTranslation } from "next-i18next";
-import posthog from "posthog-js";
import React from "react";
-import { useMount } from "react-use";
import { UserSession } from "@/utils/auth";
+import { usePostHog } from "@/utils/posthog";
import { trpc } from "../utils/trpc";
import { useRequiredContext } from "./use-required-context";
@@ -66,28 +65,18 @@ export const UserProvider = (props: {
},
});
- useMount(() => {
- posthog.init(process.env.NEXT_PUBLIC_POSTHOG_API_KEY ?? "fake token", {
- api_host: process.env.NEXT_PUBLIC_POSTHOG_API_HOST,
- opt_out_capturing_by_default: false,
- capture_pageview: false,
- capture_pageleave: false,
- autocapture: false,
- loaded: (posthog) => {
- if (!process.env.NEXT_PUBLIC_POSTHOG_API_KEY) {
- posthog.opt_out_capturing();
- }
- if (user && posthog.get_distinct_id() !== user.id) {
- posthog.identify(
- user.id,
- !user.isGuest
- ? { email: user.email, name: user.name }
- : { name: user.id },
- );
- }
- },
- });
- });
+ const posthog = usePostHog();
+
+ React.useEffect(() => {
+ if (user && posthog?.__loaded && posthog?.get_distinct_id() !== user.id) {
+ posthog?.identify(
+ user.id,
+ !user.isGuest
+ ? { email: user.email, name: user.name }
+ : { name: user.id },
+ );
+ }
+ }, [posthog, user]);
const shortName = user
? user.isGuest === false
diff --git a/apps/web/src/pages/_app.tsx b/apps/web/src/pages/_app.tsx
index 302fb6ce3..a642c472e 100644
--- a/apps/web/src/pages/_app.tsx
+++ b/apps/web/src/pages/_app.tsx
@@ -9,6 +9,8 @@ import { Inter } from "next/font/google";
import Head from "next/head";
import { appWithTranslation } from "next-i18next";
import { DefaultSeo } from "next-seo";
+import posthog from "posthog-js";
+import { PostHogProvider } from "posthog-js/react";
import React from "react";
import { Toaster } from "react-hot-toast";
@@ -33,6 +35,21 @@ type AppPropsWithLayout = AppProps<PageProps> & {
Component: NextPageWithLayout<PageProps>;
};
+if (typeof window !== "undefined" && process.env.NEXT_PUBLIC_POSTHOG_API_KEY) {
+ posthog.init(process.env.NEXT_PUBLIC_POSTHOG_API_KEY, {
+ api_host: process.env.NEXT_PUBLIC_POSTHOG_API_HOST,
+ opt_out_capturing_by_default: false,
+ capture_pageview: false,
+ capture_pageleave: false,
+ autocapture: false,
+ loaded: (posthog) => {
+ if (!process.env.NEXT_PUBLIC_POSTHOG_API_KEY) {
+ posthog.opt_out_capturing();
+ }
+ },
+ });
+}
+
const MyApp: NextPage<AppPropsWithLayout> = ({ Component, pageProps }) => {
useCrispChat();
@@ -50,7 +67,7 @@ const MyApp: NextPage<AppPropsWithLayout> = ({ Component, pageProps }) => {
const getLayout = Component.getLayout ?? ((page) => page);
return (
- <>
+ <PostHogProvider client={posthog}>
<DefaultSeo
openGraph={{
siteName: "Rallly",
@@ -83,7 +100,7 @@ const MyApp: NextPage<AppPropsWithLayout> = ({ Component, pageProps }) => {
}
`}</style>
{getLayout(<Component {...pageProps} />)}
- </>
+ </PostHogProvider>
);
};
diff --git a/apps/web/src/pages/demo.tsx b/apps/web/src/pages/demo.tsx
index d86fdb3e0..adf77c7e3 100644
--- a/apps/web/src/pages/demo.tsx
+++ b/apps/web/src/pages/demo.tsx
@@ -1,10 +1,11 @@
import { NextPage } from "next";
import { useRouter } from "next/router";
import { useTranslation } from "next-i18next";
-import posthog from "posthog-js";
import React from "react";
import { useMount } from "react-use";
+import { usePostHog } from "@/utils/posthog";
+
import FullPageLoader from "../components/full-page-loader";
import { withSession } from "../components/user-provider";
import { withAuthIfRequired, withSessionSsr } from "../utils/auth";
@@ -16,10 +17,10 @@ const Demo: NextPage = () => {
const router = useRouter();
const createDemo = trpc.polls.demo.create.useMutation();
-
+ const posthog = usePostHog();
useMount(async () => {
const urlId = await createDemo.mutateAsync();
- posthog.capture("create demo poll");
+ posthog?.capture("create demo poll");
router.replace(`/admin/${urlId}`);
});
diff --git a/apps/web/src/utils/posthog.ts b/apps/web/src/utils/posthog.ts
new file mode 100644
index 000000000..877373ac2
--- /dev/null
+++ b/apps/web/src/utils/posthog.ts
@@ -0,0 +1,5 @@
+import { usePostHog as usePostHogHook } from "posthog-js/react";
+
+// Seems silly but annoyingly typescript tries to import usePostHog from
+// posthog-js/react/dist/types which doesn't even work.
+export const usePostHog = usePostHogHook;