🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Advanced Analytics: Events, Funnels, and A/B Tests

Next.js FeaturesđŸŸĸ Free Lesson

Advanced Analytics: Events, Funnels, and A/B Tests

Dashboards fail long before the charting library does. The usual story is that a team ships a handful of loosely named events, someone builds a conversion chart on top of them, two engineers disagree about what "purchase" means, and within a quarter nobody trusts the number enough to act on it. Advanced analytics is less about volume of data than about discipline: one vocabulary, one pipeline, one place where a metric is defined.

This lesson builds that discipline inside a Next.js application — an event taxonomy, a batching client, a funnel computed from raw rows, an experiment assignment that cannot drift, and the performance and privacy constraints that decide whether any of it is even collectable.

Prerequisites

  • !React client components and hooks
  • !Route handlers and environment variables
  • !Basic SQL for aggregation

What You'll Learn

  • 1Define an event vocabulary that survives rewrites and team changes
  • 2Batch and flush analytics events without losing data on navigation
  • 3Compute a conversion funnel from raw event rows
  • 4Assign experiment variants deterministically and detect broken experiments

An event vocabulary you can defend

Start with three distinctions that prevent most future arguments. An event is something that happened; properties describe it; identities tie it to a person or a session. Record events at moments a user would recognise as actions — checkout started, note saved, plan upgraded — not at moments convenient for your component tree, so a refactor does not change the meaning of the data.

ConventionRuleExample
Event nameobject in singular, then action in past tensenote_saved
Property namingsnake_case, consistent unitsduration_ms, plan_tier
Identitystable anonymous id plus user id when knownanon_id, user_id
Contextapp version, locale, route attached automaticallyapp_version: 4.2.0
Prohibitedfree-text input, emails, card numbers, full URLs with query secrets—

Write the dictionary down in one file that both the client and the warehouse import. When marketing asks for "engagement", the definition is a query against named events rather than a negotiation. Version the dictionary when a meaning changes: renaming purchase to order_completed without a mapping breaks every historical trend line, so emit both during a transition window and record which version produced the row.

The pipeline: hook, queue, endpoint

Firing one network request per click is a mistake for three reasons: requests race and arrive out of order, browsers drop them during unload, and a page with twenty tracked interactions costs twenty round trips. Batch instead — accumulate events in memory, flush on an interval or when the queue reaches a size, and use the beacon API on page hide so the last few events survive navigation.

'use client';
import { useCallback, useEffect, useRef } from 'react';

const FLUSH_INTERVAL_MS = 5000;
const FLUSH_AT = 20;

export function useAnalytics() {
  const queue = useRef([]);
  const timer = useRef(null);

  const flush = useCallback(async (reason) => {
    const batch = queue.current.splice(0, queue.current.length);
    if (batch.length === 0) return;

    const body = JSON.stringify({ events: batch, reason });
    if (reason === 'pagehide' && navigator.sendBeacon) {
      navigator.sendBeacon('/api/analytics', body);
      return;
    }
    await fetch('/api/analytics', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body,
      keepalive: reason === 'pagehide',
    });
  }, []);

  const track = useCallback((name, properties = {}) => {
    queue.current.push({
      name,
      properties,
      ts: Date.now(),
      path: window.location.pathname,
      anon_id: window.localStorage.getItem('anon_id'),
    });
    if (queue.current.length >= FLUSH_AT) flush('size');
  }, [flush]);

  useEffect(() => {
    timer.current = setInterval(() => flush('interval'), FLUSH_INTERVAL_MS);
    window.addEventListener('pagehide', () => flush('pagehide'));
    return () => {
      clearInterval(timer.current);
      flush('unmount');
    };
  }, [flush]);

  return { track };
}

The server side should validate every batch, stamp it with server time to blunt client clock skew, attach the session identity from a cookie, and append to a queue that lands in a warehouse — never write analytics rows directly into your primary database from the request path. A slow or failing analytics endpoint must never slow the feature it is measuring, so the route handler should respond quickly and do its durability work out of band.

Turning raw rows into a funnel

A funnel is a definition, not a chart: ordered steps, a conversion window, and a rule about what happens when a user repeats a step. The hard questions are answered in SQL long before anyone picks a colour for the bars. Because every step must be attributed to the moment the user entered the funnel, the query first collapses each user to their first occurrence of each step, then applies the window:

WITH firsts AS (
  SELECT
    anon_id,
    MIN(CASE WHEN name = 'checkout_started' THEN ts END) AS t0,
    MIN(CASE WHEN name = 'payment_submitted' THEN ts END) AS t1,
    MIN(CASE WHEN name = 'purchase_completed' THEN ts END) AS t2
  FROM events
  WHERE ts >= DATE '2026-01-01'
    AND name IN ('checkout_started', 'payment_submitted', 'purchase_completed')
  GROUP BY anon_id
)
SELECT
  COUNT(*) FILTER (WHERE t0 IS NOT NULL) AS started,
  COUNT(*) FILTER (WHERE t0 IS NOT NULL AND t1 BETWEEN t0 AND t0 + INTERVAL '24 hours') AS reached_payment,
  COUNT(*) FILTER (WHERE t0 IS NOT NULL AND t2 BETWEEN t0 AND t0 + INTERVAL '24 hours') AS purchased,
  ROUND(100.0 * COUNT(*) FILTER (WHERE t0 IS NOT NULL AND t2 BETWEEN t0 AND t0 + INTERVAL '24 hours')
        / NULLIF(COUNT(*) FILTER (WHERE t0 IS NOT NULL), 0), 1) AS conversion_pct
FROM firsts;

State the window out loud: twenty-four hours is a product decision, not a law of nature. Decide whether users may re-enter the funnel, whether a later step can arrive without an earlier one, and whether bots are excluded — then write those rules next to the query so the next analyst inherits your reasoning instead of rediscovering your assumptions.

A/B testing without lying to yourself

The experiment that ruins trust is the one where a user sees variant A, reloads, and sees variant B. Assignment must be deterministic from something the user already has — a hash of the anonymous id and the experiment name — and stored so it survives across sessions and devices where possible.

// lib/experiments.js
const MODULUS = 10000;

function fnv1a(input) {
  let hash = 0x811c9dc5;
  for (let i = 0; i < input.length; i++) {
    hash ^= input.charCodeAt(i);
    hash = Math.imul(hash, 0x01000193) >>> 0;
  }
  return hash >>> 0;
}

export function assignVariant(anonId, experimentName, weights = { control: 50, treatment: 50 }) {
  const bucket = fnv1a(experimentName + ':' + anonId) % MODULUS;
  let cursor = 0;
  for (const [variant, percent] of Object.entries(weights)) {
    cursor += (percent / 100) * MODULUS;
    if (bucket < cursor) return { variant, bucket };
  }
  return { variant: Object.keys(weights)[0], bucket };
}

Two disciplines keep the result honest. First, check sample ratio mismatch: if you asked for a fifty-fifty split and observed forty-two percent, something upstream is dropping or double-counting traffic, and the result is invalid regardless of the p-value. Second, decide your stopping rule before launch — repeated peeking at an underpowered result is a reliable way to declare a winner from noise. Holdout guardrail metrics matter just as much: a variant that lifts clicks while inflating support tickets is not a win.

Real user performance numbers

Lab scores describe a device you do not own. Field data from actual sessions tells you what the 95th percentile experiences, and in the current metrics the interaction responsiveness figure replaced the old long-task metric as a core signal. Collect it from real sessions, attach the route name, and report percentiles rather than averages — a mean hides the slow tail that produces the complaints.

'use client';
import { useEffect } from 'react';
import { onLCP, onINP, onCLS, onTTFB } from 'web-vitals';

function send(metric) {
  const body = JSON.stringify({
    name: metric.name,
    value: Math.round(metric.value * 100) / 100,
    rating: metric.rating,
    route: window.location.pathname,
    navigation_type: metric.navigationType,
  });
  if (navigator.sendBeacon) navigator.sendBeacon('/api/vitals', body);
  else fetch('/api/vitals', { method: 'POST', body, keepalive: true });
}

export function WebVitals() {
  useEffect(() => {
    onLCP(send);
    onINP(send);
    onCLS(send);
    onTTFB(send);
  }, []);
  return null;
}

Tie performance back to the funnel. If conversion on the checkout route drops at the same hour the 75th percentile interaction delay doubles, you have found a revenue bug that no amount of event counting would have surfaced.

Cardinality, sampling, and consent

Every property you add multiplies the number of distinct series a metrics backend stores. Free-text properties are the classic mistake: a URL or a search query as a label explodes cardinality and quietly increases your bill while making every dashboard slower.

ConcernNaive approachDefensible approach
CardinalityUnbounded user text as a labelBounded enums, hashed ids, bucketed numbers
Volume100 percent of page viewsSample routine events, keep 100 percent of conversions
ConsentCollect first, ask laterGate the whole pipeline on the consent state
RetentionKeep everything foreverTime-partition and drop raw rows on a schedule
IdentityThird-party cookiesFirst-party id plus server-side session join

Sampling deserves one warning: sample consistently. If you keep one in ten sessions for page views but every conversion, your conversion rate is still correct only if the denominator is scaled the same way. Document the rule in the metric definition rather than in someone's head.

Questions that decide whether anyone trusts the numbers

Before a metric reaches an executive dashboard, it should survive four questions. What exactly counts as this event, and where is that written down? Which users are excluded, and why? What happens to the number when traffic doubles or the definition changes? And if two teams compute it independently, do they agree? When the answer to the last question is no, the fix is never a better chart — it is moving the definition into one shared module and one shared query.

Common Mistakes

Firing a network request for every tracked interaction

Fix: Batch in memory and flush on an interval, a size threshold, or page hide with the beacon API.

Naming events after components instead of user actions

Fix: Name events after what the user did so a refactor does not change the meaning of historical data.

Using free-text input as a metric label

Fix: Bound properties to enums or hash them; unbounded labels explode cardinality and cost.

Re-randomising the variant on every render or reload

Fix: Hash the anonymous id with the experiment name and persist the assignment.

Reading significance while the test is still underpowered

Fix: Pre-commit to a sample size or duration and check sample ratio mismatch before trusting any result.

Letting the analytics endpoint block the feature

Fix: Respond fast and do durability work out of band; a failed metric should never break a user action.

Best Practices

  • Keep the event dictionary in one module imported by client, server, and warehouse jobs
  • Stamp batches with server time and attach identity from a cookie rather than trusting the client
  • Document each metric's window, exclusions, and sampling rule next to its definition
  • Join performance percentiles to funnel conversion to find revenue-impacting regressions
  • Gate the entire pipeline on consent and delete raw rows on a published schedule

Interview Questions

Q1: How do you keep an A/B test assignment stable across sessions?

Derive it deterministically from a hash of the anonymous id and experiment name, persist the result, and use weighted bucket ranges so the split matches the requested ratio.

Q2: What is sample ratio mismatch and why does it invalidate a test?

The observed split differs from the assigned ratio, which means traffic is being dropped or duplicated somewhere in the pipeline, so the comparison groups are no longer exchangeable.

Q3: Why batch analytics events on the client?

Per-event requests race, are dropped during unload, and cost round trips; batching with a beacon flush preserves order and survives navigation.

Q4: How would you define checkout conversion for two teams that disagree?

Move the definition into a shared query with an explicit step list, conversion window, and exclusion rules, then have both teams consume that single implementation.

Key Takeaways

  • Trust collapses when event names are ambiguous; write a versioned dictionary and import it everywhere.
  • Batch client events and flush with sendBeacon so navigation does not eat the last interactions.
  • A funnel is a stated definition — ordered steps, window, re-entry and bot rules — expressed once in SQL.
  • Experiment assignment must be deterministic, and sample ratio mismatch is the first thing to check.
  • Field performance percentiles, not lab averages, reveal the slowness that actually costs conversions.
  • Bound cardinality, gate on consent, and publish retention rules before the data volume becomes a liability.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement