Fix Posthog Tracking (#71)

* Use simple API calls for Posthog Tracking to increase compatibility
This commit is contained in:
Matthias Nannt
2022-08-25 18:59:41 +02:00
committed by GitHub
parent f26e14df12
commit c674d58c69
7 changed files with 54 additions and 47 deletions
+26 -16
View File
@@ -1,25 +1,35 @@
import getConfig from "next/config";
import { PostHog } from "posthog-node";
import { hashString } from "./utils";
const { serverRuntimeConfig } = getConfig();
const enabled =
serverRuntimeConfig.posthogApiKey && serverRuntimeConfig.posthogApiHost;
process.env.NODE_ENV === "production" &&
serverRuntimeConfig.posthogApiKey &&
serverRuntimeConfig.posthogApiHost;
export const caputurePosthogEvent = (userId, eventName, properties = {}) => {
export const caputurePosthogEvent = async (
userId,
eventName,
properties = {}
) => {
if (!enabled) {
return;
}
const client = new PostHog(
serverRuntimeConfig.posthogApiKey,
{ host: serverRuntimeConfig.posthogApiHost } // You can omit this line if using PostHog Cloud
);
client.capture({
distinctId: userId,
event: eventName,
properties,
});
// On program exit, call shutdown to stop pending pollers and flush any remaining events
client.shutdown();
try {
await fetch(`${serverRuntimeConfig.posthogApiHost}/capture/`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
api_key: serverRuntimeConfig.posthogApiKey,
event: eventName,
properties: {
distinct_id: hashString(userId),
...properties,
},
timestamp: new Date().toISOString(),
}),
});
} catch (error) {
console.error("error sending posthog event:", error);
}
};
+21 -16
View File
@@ -1,6 +1,5 @@
import getConfig from "next/config";
import { PostHog } from "posthog-node";
import crypto from "crypto";
import { hashString } from "./utils";
const { serverRuntimeConfig } = getConfig();
@@ -9,21 +8,27 @@ const { serverRuntimeConfig } = getConfig();
and we cannot trace anything back to you or your customers. If you still want to
disable telemetry, set the environment variable TELEMETRY_DISABLED=1 */
export const sendTelemetry = (event: string) => {
export const sendTelemetry = async (eventName: string) => {
if (
serverRuntimeConfig.nextauthUrl !== "http://localhost:3000" &&
!serverRuntimeConfig.telemetryDisabled
!serverRuntimeConfig.telemetryDisabled &&
process.env.NODE_ENV === "production" &&
serverRuntimeConfig.nextauthUrl !== "http://localhost:3000"
) {
const client = new PostHog(
"phc_BTq4eagaCzPyUSURXVYwlScTQRvcmBDXjYh7OG6kiqw",
{ host: "https://posthog.snoopforms.com" }
);
client.capture({
distinctId: crypto
.createHash("sha256")
.update(serverRuntimeConfig.nextauthUrl)
.digest("hex"),
event,
});
try {
await fetch("https://posthog.snoopforms.com/capture/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
api_key: "phc_BTq4eagaCzPyUSURXVYwlScTQRvcmBDXjYh7OG6kiqw",
event: eventName,
properties: {
distinct_id: hashString(serverRuntimeConfig.nextauthUrl),
},
timestamp: new Date().toISOString(),
}),
});
} catch (error) {
console.log("error sending telemetry:", error);
}
}
};
+5
View File
@@ -1,5 +1,6 @@
import intlFormat from "date-fns/intlFormat";
import { formatDistance } from "date-fns";
import crypto from "crypto";
export const fetcher = async (url) => {
const res = await fetch(url);
@@ -127,3 +128,7 @@ export const generateId = (length) => {
}
return result;
};
export const hashString = (string: string) => {
return crypto.createHash("sha256").update(string).digest("hex");
};
-1
View File
@@ -30,7 +30,6 @@
"next-auth": "^4.10.1",
"nextjs-cors": "^2.1.1",
"nodemailer": "^6.7.7",
"posthog-node": "^2.0.2",
"react": "17.0.2",
"react-chartjs-2": "^4.3.1",
"react-dom": "17.0.2",
+1 -1
View File
@@ -57,7 +57,7 @@ export default async function handle(
owner: { connect: { email: session?.user?.email } },
},
});
caputurePosthogEvent(session.user.email, "formCreated");
caputurePosthogEvent(session.user.email, "form created");
res.json(result);
}
+1 -1
View File
@@ -28,7 +28,7 @@ export default async function handle(
},
});
if (!emailVerificationDisabled) await sendVerificationEmail(userData);
caputurePosthogEvent(user.email, "userCreated");
caputurePosthogEvent(user.email, "user created");
res.json(userData);
} catch (e) {
if (e.code === "P2002") {
-12
View File
@@ -2126,13 +2126,6 @@ postcss@^8.4.13, postcss@^8.4.14:
picocolors "^1.0.0"
source-map-js "^1.0.2"
posthog-node@^2.0.2:
version "2.0.2"
resolved "https://registry.yarnpkg.com/posthog-node/-/posthog-node-2.0.2.tgz#f2a5b087d512508dd5b7cf996c0bc7a873840742"
integrity sha512-lB7y5znEGHhL6CP+Xwq4v+js4x0oGqyJXwZM2SXPXakZzPq+UQo/HLYZCOnsCpk8DnXLZOKjut9vYLqkTCjGJQ==
dependencies:
undici "^5.8.0"
preact-render-to-string@^5.1.19:
version "5.2.1"
resolved "https://registry.yarnpkg.com/preact-render-to-string/-/preact-render-to-string-5.2.1.tgz#71f3e8cda65f33dbc8ad8d904ff58e3f532e59f3"
@@ -2670,11 +2663,6 @@ unbox-primitive@^1.0.2:
has-symbols "^1.0.3"
which-boxed-primitive "^1.0.2"
undici@^5.8.0:
version "5.9.1"
resolved "https://registry.yarnpkg.com/undici/-/undici-5.9.1.tgz#fc9fd85dd488f965f153314a63d9426a11f3360b"
integrity sha512-6fB3a+SNnWEm4CJbgo0/CWR8RGcOCQP68SF4X0mxtYTq2VNN8T88NYrWVBAeSX+zb7bny2dx2iYhP3XHi00omg==
update-browserslist-db@^1.0.5:
version "1.0.5"
resolved "https://registry.yarnpkg.com/update-browserslist-db/-/update-browserslist-db-1.0.5.tgz#be06a5eedd62f107b7c19eb5bcefb194411abf38"