Skip to content

Commit

Permalink
fix(website): posthog analytics
Browse files Browse the repository at this point in the history
  • Loading branch information
not-ani committed Nov 20, 2024
1 parent 5ea7d4a commit df48b3e
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 4 deletions.
26 changes: 26 additions & 0 deletions apps/website/src/app/_analytics/capture.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// app/PostHogPageView.jsx
"use client";

import { useEffect } from "react";
import { usePathname, useSearchParams } from "next/navigation";
import { usePostHog } from "posthog-js/react";

export default function PostHogPageView() {
const pathname = usePathname();
const searchParams = useSearchParams();
const posthog = usePostHog();
useEffect(() => {
// Track pageviews
if (pathname && posthog) {
let url = window.origin + pathname;
if (searchParams.toString()) {
url = url + `?${searchParams.toString()}`;
}
posthog.capture("$pageview", {
$current_url: url,
});
}
}, [pathname, searchParams, posthog]);

return null;
}
14 changes: 11 additions & 3 deletions apps/website/src/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import "~/app/globals.css";

import type { Metadata } from "next";
import dynamic from "next/dynamic";
import { GeistSans } from "geist/font/sans";

import { CSPostHogProvider } from "./provides/posthog";
Expand Down Expand Up @@ -69,16 +70,23 @@ export const metadata: Metadata = {
],
};

const PostHogPageView = dynamic(() => import("./_analytics/capture"), {
ssr: false,
});

export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" className={`${GeistSans.variable}`}>
<body>
<CSPostHogProvider>{children}</CSPostHogProvider>
</body>
<CSPostHogProvider>
<body>
<PostHogPageView />
{children}
</body>
</CSPostHogProvider>
</html>
);
}
5 changes: 4 additions & 1 deletion apps/website/src/app/provides/posthog.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
/* eslint-disable no-restricted-properties */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
//@ts-nocheck
"use client";

Expand All @@ -7,7 +9,8 @@ import { PostHogProvider } from "posthog-js/react";
if (typeof window !== "undefined") {
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
person_profiles: "identified_only", // or 'always' to create profiles for anonymous users as well
person_profiles: "anonymous", // or 'always' to create profiles for anonymous users as well
capture_pageleave: true, // Enable pageleave capture
});
}
export function CSPostHogProvider({ children }: { children: React.ReactNode }) {
Expand Down

0 comments on commit df48b3e

Please sign in to comment.