Skip to main content
Early access — new tools and guides added regularly
🔴 Launch a Business — Guide 14 of 19
View track
>_ claude codeIntermediate30 min

Product Analytics with AI Insights

Build a product analytics system with event tracking, funnel analysis, cohort reports, and AI-generated insights that reveal what your data means.

What you will build
A product analytics dashboard with funnels, cohorts, and automated insight generation
Prerequisites
Getting Started with Claude Codeuser-analytics-growth-metrics

Why product analytics matters for startups

Product analytics tells you what users actually do in your application — not what they say they do, not what you assume they do. Without analytics, you are guessing. With analytics, you are deciding. The core concept is event tracking: recording every meaningful action a user takes. A user signs up (event: user_signed_up), views the pricing page (event: page_viewed, property: page=/pricing), starts a trial (event: trial_started), and eventually pays (event: subscription_created, property: plan=pro). This chain of events tells a story. Product analytics answers questions like: where do users drop off in the onboarding flow? Which feature correlates most strongly with retention? How long does it take a typical user to go from signup to first value? Ask Claude Code: Create a Next.js project with TypeScript, Tailwind, and Prisma for a product analytics dashboard. Define the database schema. Event (id, userId, eventName, properties as JSON, timestamp, sessionId, pageUrl, referrer). User (id, externalId for mapping to your app's user ID, firstSeenAt, lastSeenAt, totalEvents, properties as JSON for user attributes like plan and company). Session (id, userId, startedAt, endedAt, eventCount, entryPage, exitPage, duration in seconds). Create an event ingestion API. Ask Claude Code: Build a POST /api/events endpoint that accepts a batch of events (up to 100 per request). Validate each event has an eventName and timestamp. Store events in the database. Update the user's lastSeenAt and totalEvents. Update or create the session based on a 30-minute inactivity window — if more than 30 minutes has passed since the last event from this user, start a new session. Seed the database with 10,000 sample events from 200 simulated users over 30 days to have realistic data for the dashboard.

Event tracking implementation

A tracking system has two sides: the client SDK that captures events from your application and the server that stores and processes them. Ask Claude Code: Create a lightweight client SDK at src/lib/analytics-sdk.ts. The SDK exports an analytics object with three methods. track(eventName, properties) records a custom event. identify(userId, traits) associates the anonymous visitor with a known user ID and stores traits like name, email, and plan. page(pageName, properties) records a page view with the current URL, referrer, and any custom properties. The SDK should batch events and send them every 5 seconds or when 10 events are queued, whichever comes first. Batching reduces network requests. Generate an anonymous ID (stored in localStorage) for users before they log in. When identify is called, merge the anonymous events with the identified user. Ask Claude Code: Build automatic tracking that captures common events without manual instrumentation. Track page views automatically on route changes (use Next.js router events). Track clicks on elements with a data-track attribute (e.g., data-track="cta-clicked" on a button). Track form submissions. Track rage clicks (multiple rapid clicks on the same element — usually indicates frustration). Track scroll depth milestones (25 percent, 50 percent, 75 percent, 100 percent). Add a debug mode. Ask Claude Code: When debug mode is enabled (via a URL parameter like ?analytics_debug=true), show a floating panel in the corner of the page that lists every tracked event in real-time. Each event shows the name, properties, and timestamp. This makes it easy to verify tracking is working correctly during development. Common error: sending events on every keystroke or mouse movement floods your database. Only track meaningful actions — button clicks, form submissions, navigation, and feature usage. A good rule: if the event does not help you make a product decision, do not track it.

Funnel analysis

A funnel tracks how users progress through a sequence of steps. The classic example: visited homepage, clicked signup, completed registration, activated account, made first purchase. At each step, some users continue and some drop off. The funnel shows you where the biggest losses are. Ask Claude Code: Create a funnel analysis engine at src/lib/funnels.ts. A funnel definition is an array of steps, each with an event name and optional property filters. The engine takes a funnel definition and a date range, queries the database for users who completed each step in order, and returns the count and percentage at each step. Crucially, the steps must happen in order — a user who made a purchase but never completed registration does not count as having passed the registration step. Build the funnel UI. Ask Claude Code: Create a FunnelChart component that displays the funnel as a horizontal bar chart. Each bar represents a step and is proportionally sized to the number of users. Between bars, show the conversion rate (percentage who continued to the next step) and the absolute drop-off count. Use green for healthy conversion rates (above 50 percent) and red for poor rates (below 20 percent). Add a compare feature that overlays two date ranges so you can see if conversion improved after a change. Create a pre-built funnel library. Ask Claude Code: Define common funnels: Signup Funnel (visited landing page, clicked CTA, started signup form, completed signup, verified email), Onboarding Funnel (signed up, completed profile, used first feature, invited a teammate, upgraded to paid), and Purchase Funnel (viewed product, added to cart, started checkout, completed payment). Let users create custom funnels by selecting events from a dropdown and arranging them in order. Add time-based analysis to funnels. Ask Claude Code: Show the median time between each funnel step. If users take 3 days on average between signup and first feature use, that 3-day gap is where onboarding improvements can have the biggest impact. Highlight steps where the median time is unusually long. Common error: funnels must use the same user across all steps. Do not count unique events per step — count unique users who completed all previous steps and then completed the current step.

Cohort analysis and retention

Cohort analysis groups users by when they signed up and tracks their behaviour over time. It answers the most important question in SaaS: are you retaining users? Ask Claude Code: Create a cohort analysis engine at src/lib/cohorts.ts. A cohort is defined by a grouping event (usually signup) and a return event (usually any active event or a specific feature use). The engine creates a matrix: rows are cohorts (users who signed up in week 1, week 2, week 3), columns are time periods after signup (week 0, week 1, week 2, up to week 12). Each cell shows the percentage of users from that cohort who performed the return event during that time period. Build the cohort table UI. Ask Claude Code: Create a CohortTable component that renders the retention matrix as a colour-coded table. Each cell's background colour represents the retention percentage: dark green for high retention (above 60 percent), light green for moderate (30 to 60 percent), yellow for concerning (10 to 30 percent), red for poor (below 10 percent). The first column (week 0) should always be 100 percent since all users are active in their signup week. Hover over a cell to see the exact count and percentage. Add cohort comparison. Ask Claude Code: Let users compare cohorts before and after a product change. If you shipped a new onboarding flow in week 5, compare the retention curves of cohorts from weeks 1 to 4 (old onboarding) versus weeks 6 to 9 (new onboarding). Show both curves on a line chart — if the new onboarding is better, its retention curve should be higher at every time period. Build a retention alert. Ask Claude Code: Calculate the average retention at each period across all cohorts. When a new cohort's retention drops significantly below the historical average (more than 2 standard deviations), trigger an alert: Week 12 cohort retention at week 4 is 18 percent, which is significantly below the historical average of 34 percent. Investigate. This catches retention problems early, before they compound into churn crises. Common error: small cohorts produce noisy data. If only 5 users signed up in a given week, one user returning or not changes retention by 20 percentage points. Show a confidence indicator for small cohorts or require a minimum cohort size.

AI-generated insights

Raw analytics data is useful. AI-interpreted analytics data is powerful. Instead of staring at charts and hoping patterns emerge, let AI analyse the data and surface insights in plain English. Ask Claude Code: Create an insight generation system at src/lib/insights.ts. Define insight types: TrendInsight (a metric is increasing or decreasing significantly), AnomalyInsight (an unusual data point was detected), CorrelationInsight (two metrics are moving together), and OpportunityInsight (a specific segment is underperforming but could be improved). Build automated insight detection. Ask Claude Code: Create functions that analyse the analytics data and generate insights. Trend detection: compare this week's metrics to last week's and last month's. If signup rate increased by more than 20 percent week-over-week, generate an insight. Anomaly detection: calculate the rolling average and standard deviation for key metrics. Flag any day where a metric is more than 2 standard deviations from the mean. Correlation detection: check if feature usage correlates with retention. If users who use Feature X in their first week have 2x the retention of users who do not, that is a critical insight. Drop-off detection: scan all funnels for steps with unusually low conversion and generate recommendations. Format insights as natural language. Ask Claude Code: Create an InsightCard component that shows each insight with a clear headline (Signup rate increased 35 percent this week), a brief explanation of why this matters, a chart or data visualisation supporting the insight, and a suggested action (Investigate the traffic source — organic search referrals doubled). Generate 5 to 10 insights daily and show them on the dashboard homepage. Rank by impact — insights about revenue-affecting metrics should appear first. Let users mark insights as Noted (acknowledge without acting), In Progress (investigating), or Resolved (addressed). Common error: AI insights must be grounded in real data. Always show the underlying numbers alongside the narrative so users can verify the insight. Never generate insights from insufficient data — if you have fewer than 100 events for a metric, the sample is too small for meaningful trend detection.

Dashboard design and deployment

The analytics dashboard should provide a clear overview at a glance with the ability to drill into details. Ask Claude Code: Create the main dashboard page at src/app/dashboard/page.tsx with these sections. KPI bar: a row of 6 key metrics as cards — daily active users, new signups, conversion rate, retention rate (week 1), average session duration, and total events tracked. Each card shows the current value, trend arrow with percentage change, and a sparkline of the last 14 days. AI Insights: the top 3 insights for today, each as a compact card with the headline and a View Details button. Active Funnel: the primary conversion funnel (signup to activation) shown as a compact horizontal chart. User Activity: a heatmap showing event volume by hour and day of week — reveals when your users are most active. Recent Events: a live feed of the last 20 events, updating in real-time (use polling every 10 seconds). Add a date range picker that controls all dashboard components. Ask Claude Code: Build a global date range selector in the dashboard header. Preset options: today, last 7 days, last 30 days, last quarter, and custom range. When the range changes, all KPIs, charts, and insights recalculate. Show a comparison toggle that overlays the previous equivalent period (for last 7 days, compare to the 7 days before that). Build individual analytics pages for deeper analysis. Ask Claude Code: Create pages for Funnels (list all defined funnels with their current conversion rates, click to see the full funnel analysis), Cohorts (the retention matrix with configuration options), Events (searchable list of all event types with frequency counts, click an event to see its trend and property breakdowns), and Users (individual user lookup — search by email or ID, see their complete event timeline). Deploy to Vercel with a PostgreSQL database. Ask Claude Code: Configure the project with proper environment variables, database connection pooling for production, and caching for expensive analytics queries. Add a tracking code snippet page that shows users how to add the analytics SDK to their own applications — a single script tag or npm install command. The analytics platform is complete — a self-hosted alternative to Mixpanel, Amplitude, or PostHog that costs a fraction of the price and gives you full control over your data.

Related Lesson

Data-Driven Decision Making

This guide is hands-on and practical. The full curriculum covers the conceptual foundations in depth with structured lessons and quizzes.

Go to lesson