Skip to content

Commit 022e845

Browse files
committed
server-side posthog
1 parent 29f6092 commit 022e845

3 files changed

Lines changed: 54 additions & 19 deletions

File tree

apps/website/app/utils/internalErrorSsr.ts

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,22 @@
1-
import { posthog, type Properties } from "posthog-js";
1+
import { PostHog } from "posthog-node";
22

3-
let initialized = false;
3+
let posthog: PostHog | undefined;
44

5-
const doInitPostHog = (): void => {
6-
if (initialized) return;
7-
if (
8-
!process.env.NEXT_PUBLIC_POSTHOG_KEY ||
9-
!process.env.NEXT_PUBLIC_POSTHOG_HOST
10-
) {
11-
throw new Error("PostHog environment variables are not set");
5+
const getPostHog = (): PostHog => {
6+
if (posthog === undefined) {
7+
if (
8+
!process.env.NEXT_PUBLIC_POSTHOG_KEY ||
9+
!process.env.NEXT_PUBLIC_POSTHOG_HOST
10+
) {
11+
throw new Error("PostHog environment variables are not set");
12+
}
13+
posthog = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
14+
host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
15+
flushAt: 1,
16+
flushInterval: 0,
17+
});
1218
}
13-
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
14-
/* eslint-disable @typescript-eslint/naming-convention */
15-
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
16-
capture_pageview: false,
17-
/* eslint-enable @typescript-eslint/naming-convention */
18-
});
19-
initialized = true;
19+
return posthog;
2020
};
2121

2222
const NON_WORD = /\W+/g;
@@ -28,13 +28,12 @@ export const internalError = ({
2828
}: {
2929
error: unknown;
3030
type?: string;
31-
context?: Properties;
31+
context?: object;
3232
forceSendInDev?: boolean;
3333
}): void => {
3434
if (process.env.NODE_ENV === "development" && forceSendInDev !== true) {
3535
console.error(error);
3636
} else {
37-
doInitPostHog();
3837
type = type || "Internal Error";
3938
const slugType = type.replaceAll(NON_WORD, "-").toLowerCase();
4039
context = {
@@ -52,7 +51,12 @@ export const internalError = ({
5251
error = new Error(typeof error);
5352
}
5453
}
55-
posthog.captureException(error, { ...context, type: slugType });
54+
const posthog = getPostHog();
55+
const result = posthog.captureException(error, undefined, {
56+
...context,
57+
type: slugType,
58+
});
59+
console.error(result);
5660
if (process.env.NODE_ENV === "development") console.error(error);
5761
}
5862
};

apps/website/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
"nextra-theme-docs": "^4.6.1",
2828
"openai": "^4.98.0",
2929
"posthog-js": "catalog:",
30+
"posthog-node": "^5.34.2",
3031
"react": "catalog:",
3132
"react-dom": "catalog:",
3233
"resend": "^4.0.1",

pnpm-lock.yaml

Lines changed: 30 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)