Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wip: router agnostic posthog component #898

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions src/providers/PosthogAnalytics.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// app/providers.tsx
'use client';

import { Suspense, useEffect } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
import { useRouterType } from '@hooks/useRouterType';
import posthog, { PostHogConfig } from 'posthog-js';
import { PostHogProvider } from 'posthog-js/react';

import { env } from '@utils/env';

const phConfig: Partial<PostHogConfig> = {
api_host: 'https://mikebifulco.com/ingest',
person_profiles: 'identified_only',
capture_pageview: false, // Disable automatic pageview capture, as we capture manually
} as const;

export function PHProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
posthog.init(env.NEXT_PUBLIC_POSTHOG_KEY, phConfig);
}, []);

return <PostHogProvider client={posthog}>{children}</PostHogProvider>;
}

// New component to track page views
const PosthogPageView = () => {
const pathname = usePathname();
const searchParams = useSearchParams();

useEffect(() => {
if (!pathname) return;

const searchParamsString = searchParams?.toString() ?? '';
const url = window.origin + pathname + searchParamsString;
posthog.capture('$pageview', {
$current_url: url,
});
}, [pathname, searchParams]);

return null;
};

const PosthogAppRouter = () => {
return (
<Suspense fallback={null}>
<PosthogPageView />
</Suspense>
);
};

/**
* This component is used to integrate Posthog with Next.js,
* and adjusts itself depending on the current route, regardless of
* whether it's from the Pages or App Router.
*/
export const PosthogAnalytics = () => {
const routerType = useRouterType();
if (routerType === 'pages') {
return <PosthogPagesRouter />;
}
return <PosthogAppRouter />;
};

export default PHProvider;
Loading