KitRocket

Analytics Module

PostHog integration for event tracking, feature flags, session recording, and A/B testing.

Pro tier only. This module is included in the Pro plan.

Overview

KitRocket integrates PostHog for product analytics. You get:

  • Event tracking — track user actions throughout your app
  • Feature flags — roll out features to specific users or percentages
  • Session recording — watch how users interact with your app
  • A/B testing — test variations and measure impact
  • User identification — connect events to authenticated users

Analytics logic lives in src/lib/analytics/.

Configuration

Environment variables

NEXT_PUBLIC_POSTHOG_KEY="phc_your-posthog-key"
NEXT_PUBLIC_POSTHOG_HOST="https://us.i.posthog.com"

PostHog setup

  1. Create a free account at posthog.com
  2. Create a new project
  3. Go to Project Settings
  4. Copy the Project API Key and Host

Provider setup

PostHog is initialized in a React provider that wraps your app:

"use client";

import posthog from "posthog-js";
import { PostHogProvider } from "posthog-js/react";
import { useEffect } from "react";

export function AnalyticsProvider({ children }: { children: React.ReactNode }) {
  useEffect(() => {
    posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
      api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
      capture_pageview: true,
      capture_pageleave: true,
    });
  }, []);

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

Add the provider to your root layout:

import { AnalyticsProvider } from "@/lib/analytics/posthog";

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <AnalyticsProvider>{children}</AnalyticsProvider>
      </body>
    </html>
  );
}

Usage

Track events

import posthog from "posthog-js";

export function trackEvent(event: string, properties?: Record<string, unknown>) {
  posthog.capture(event, properties);
}

// Pre-defined events for consistency
export const analytics = {
  signUp: (method: string) => trackEvent("user_signed_up", { method }),
  planSelected: (plan: string) => trackEvent("plan_selected", { plan }),
  checkoutStarted: (plan: string) => trackEvent("checkout_started", { plan }),
  checkoutCompleted: (plan: string) => trackEvent("checkout_completed", { plan }),
  featureUsed: (feature: string) => trackEvent("feature_used", { feature }),
  aiMessageSent: () => trackEvent("ai_message_sent"),
};

Use in components:

import { analytics } from "@/lib/analytics/events";

function handleSelectPlan(plan: string) {
  analytics.planSelected(plan);
  router.push(`/checkout?plan=${plan}`);
}

Identify users

After login, identify the user so events are linked to their account:

export function identifyUser(user: { id: string; email: string; name: string }) {
  posthog.identify(user.id, {
    email: user.email,
    name: user.name,
  });
}

Call this after successful authentication:

import { identifyUser } from "@/lib/analytics/events";

// After login succeeds:
identifyUser({ id: session.user.id, email: session.user.email, name: session.user.name });

Feature flags

Create feature flags in the PostHog dashboard, then check them in code:

"use client";

import { useFeatureFlagEnabled } from "posthog-js/react";

export function Dashboard() {
  const showNewFeature = useFeatureFlagEnabled("new-dashboard-widget");

  return (
    <div>
      {showNewFeature && <NewDashboardWidget />}
    </div>
  );
}

Server-side flag check:

import { PostHog } from "posthog-node";

const posthogServer = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!);

export default async function DashboardPage() {
  const flagEnabled = await posthogServer.isFeatureEnabled("new-feature", userId);
  // ...
}

A/B testing

  1. Create an experiment in PostHog dashboard
  2. Define variants (e.g., "control" vs "variant")
  3. Check the variant in code:
import { useFeatureFlagVariantKey } from "posthog-js/react";

function PricingPage() {
  const variant = useFeatureFlagVariantKey("pricing-experiment");

  if (variant === "annual-first") {
    return <AnnualFirstPricing />;
  }
  return <MonthlyFirstPricing />;
}

Customization

Custom dashboards

Build PostHog dashboards to track:

  • Signup funnel (visit > register > verify > first action)
  • Revenue metrics (checkout started > completed > churned)
  • Feature adoption (which features are used most)
  • AI usage (messages sent, tokens consumed)

Disable in development

useEffect(() => {
  if (process.env.NODE_ENV === "development") return;

  posthog.init(/* ... */);
}, []);

Removing this module

  1. Delete src/lib/analytics/ directory
  2. Remove AnalyticsProvider from src/app/layout.tsx
  3. Remove all analytics.* and trackEvent calls from components
  4. Remove dependencies:
pnpm remove posthog-js posthog-node
  1. Remove NEXT_PUBLIC_POSTHOG_KEY and NEXT_PUBLIC_POSTHOG_HOST from .env.local

On this page