Claude Code for Amplitude: Behavioral Analytics and Experiments — Claude Skills 360 Blog
Blog / AI / Claude Code for Amplitude: Behavioral Analytics and Experiments
AI

Claude Code for Amplitude: Behavioral Analytics and Experiments

Published: July 25, 2027
Read time: 5 min read
By: Claude Skills 360

Amplitude provides behavioral product analytics with built-in experimentation — amplitude.init(apiKey, { defaultTracking: { pageViews: false } }) initializes. amplitude.setUserId(userId) identifies the user. amplitude.setUserProperties({ plan, role, company }) sets profile attributes. amplitude.track("Button Clicked", { name, page }) fires an event. Revenue: const revenue = new amplitude.Revenue(); revenue.setProductId("pro-plan").setPrice(49).setRevenue(49); amplitude.revenue(revenue) tracks purchases. Session Replay: amplitude.add(sessionReplayPlugin({ sampleRate: 0.1 })) records 10% of sessions. Identify operations: const identify = new Identify(); identify.set("plan", "pro").increment("loginCount", 1).append("features", "advanced"); amplitude.identify(identify) — operators set, setOnce, increment, append, prepend, unset. Group analytics: amplitude.setGroup("company", companyId) and amplitude.groupIdentify("company", companyId, new Identify().set("plan", "enterprise")). Amplitude Experiment: const experiment = Experiment.initialize(deploymentKey), await experiment.fetch({ userId }), const variant = experiment.variant("feature-flag"), if (variant.value === "treatment") showNewUI(). Claude Code generates Amplitude tracking, experiments, and revenue analytics pipelines.

CLAUDE.md for Amplitude

## Amplitude Stack
- Browser version: @amplitude/analytics-browser >= 2.x
- Node version: @amplitude/analytics-node >= 1.x
- Experiment: @amplitude/experiment-js-client >= 1.x
- Init: amplitude.init(AMPLITUDE_API_KEY, { defaultTracking: { pageViews: false, sessions: true, fileDownloads: false, formInteractions: false } })
- Identity: amplitude.setUserId(userId); amplitude.setUserProperties({ plan, email })
- Track: amplitude.track("Event Name", { prop: value })
- Identify ops: const id = new Identify(); id.set("plan", "pro").increment("sessions", 1); amplitude.identify(id)
- Session Replay: amplitude.add(sessionReplayPlugin({ sampleRate: 0.05 }))

Amplitude Browser Client

// lib/amplitude/client.ts — typed Amplitude analytics
import * as amplitude from "@amplitude/analytics-browser"
import { Identify } from "@amplitude/analytics-browser"
import { sessionReplayPlugin } from "@amplitude/plugin-session-replay-browser"

let initialized = false

export function initAmplitude() {
  if (initialized || typeof window === "undefined") return

  amplitude.init(process.env.NEXT_PUBLIC_AMPLITUDE_API_KEY!, {
    defaultTracking: {
      pageViews:         false, // manual page view tracking
      sessions:          true,
      fileDownloads:     false,
      formInteractions:  false,
    },
    autocapture:  false,
    logLevel:     process.env.NODE_ENV === "development" ? amplitude.Types.LogLevel.Debug : amplitude.Types.LogLevel.Warn,
  })

  // Session Replay — record a sample of sessions
  const sampleRate = process.env.NODE_ENV === "production" ? 0.05 : 1.0
  amplitude.add(sessionReplayPlugin({ sampleRate }))

  initialized = true
}

// ── Event catalog ──────────────────────────────────────────────────────────

type EventProperties = {
  "Page Viewed":             { pageName: string; path: string }
  "Button Clicked":          { buttonId: string; buttonText: string; page: string }
  "Feature Enabled":         { feature: string }
  "Trial Started":           { plan: string; source: string }
  "Subscription Started":    { plan: string; interval: "monthly" | "annual"; amount: number }
  "Subscription Cancelled":  { plan: string; reason?: string }
  "Invite Sent":             { method: "email" | "link"; count: number }
  "File Uploaded":           { fileType: string; sizeMb: number }
  "Export Completed":        { format: string; rowCount: number }
  "API Key Created":         { purpose?: string }
  "Error Displayed":         { errorCode: string; page: string }
}

type EventName = keyof EventProperties

export function track<E extends EventName>(
  event: E,
  properties: EventProperties[E],
): void {
  if (!initialized) return
  amplitude.track(event, properties as Record<string, unknown>)
}

// ── Identity ───────────────────────────────────────────────────────────────

export function identifyUser(
  userId: string,
  properties: {
    email?:     string
    name?:      string
    plan?:      string
    createdAt?: string
    company?:   string
    role?:      string
  } = {},
): void {
  if (!initialized) return
  amplitude.setUserId(userId)

  if (Object.keys(properties).length > 0) {
    const identify = new Identify()
    if (properties.email)     identify.setOnce("email",     properties.email)
    if (properties.name)      identify.set("name",          properties.name)
    if (properties.plan)      identify.set("plan",          properties.plan)
    if (properties.createdAt) identify.setOnce("createdAt", properties.createdAt)
    if (properties.company)   identify.set("company",       properties.company)
    if (properties.role)      identify.set("role",          properties.role)
    amplitude.identify(identify)
  }
}

export function setGroup(groupType: string, groupId: string): void {
  if (!initialized) return
  amplitude.setGroup(groupType, groupId)
}

export function groupIdentify(
  groupType: string,
  groupId: string,
  traits: Record<string, unknown>,
): void {
  if (!initialized) return
  const identify = new Identify()
  Object.entries(traits).forEach(([k, v]) => identify.set(k, v as amplitude.Types.ValidPropertyType))
  amplitude.groupIdentify(groupType, groupId, identify)
}

export function incrementUserProperty(property: string, value = 1): void {
  if (!initialized) return
  const identify = new Identify()
  identify.increment(property, value)
  amplitude.identify(identify)
}

export function trackRevenue(
  productId: string,
  price: number,
  quantity = 1,
  revenueType?: string,
): void {
  if (!initialized) return
  const revenue = new amplitude.Revenue()
  revenue.setProductId(productId).setPrice(price).setQuantity(quantity).setRevenue(price * quantity)
  if (revenueType) revenue.setRevenueType(revenueType)
  amplitude.revenue(revenue)
}

export function resetIdentity(): void {
  if (!initialized) return
  amplitude.reset()
}

Amplitude Experiment (A/B Testing)

// lib/amplitude/experiment.ts — A/B experiments with Amplitude Experiment
import { Experiment } from "@amplitude/experiment-js-client"

let experiment: ReturnType<typeof Experiment.initialize> | null = null

export function initExperiment() {
  if (experiment || typeof window === "undefined") return
  experiment = Experiment.initialize(process.env.NEXT_PUBLIC_AMPLITUDE_EXPERIMENT_KEY!, {
    fetchTimeoutMillis: 5000,
    retryFetchOnFailure: true,
    automaticFetchOnAmplitudeIdentityChange: true,
  })
}

export async function fetchExperiments(userId: string): Promise<void> {
  if (!experiment) initExperiment()
  await experiment!.fetch({ userId })
}

export type ExperimentVariant = { value?: string; payload?: unknown }

export function getVariant(flagKey: string, fallback = "control"): ExperimentVariant {
  if (!experiment) return { value: fallback }
  return experiment.variant(flagKey) ?? { value: fallback }
}

// React hook:
// function useVariant(flagKey: string, fallback = "control") {
//   const variant = getVariant(flagKey, fallback)
//   return variant.value ?? fallback
// }
//
// Usage:
// const checkoutVariant = useVariant("new-checkout-flow")
// return checkoutVariant === "treatment" ? <NewCheckout /> : <OldCheckout />

Next.js Provider

// components/AmplitudeProvider.tsx — init, identity, page views
"use client"
import { useEffect } from "react"
import { usePathname } from "next/navigation"
import {
  initAmplitude,
  identifyUser,
  track,
  fetchExperiments,
} from "@/lib/amplitude/client"

type Props = {
  userId?:    string
  userEmail?: string
  userPlan?:  string
  company?:   string
  children:   React.ReactNode
}

export default function AmplitudeProvider({
  userId,
  userEmail,
  userPlan,
  company,
  children,
}: Props) {
  const pathname = usePathname()

  useEffect(() => {
    initAmplitude()
    if (userId) {
      identifyUser(userId, { email: userEmail, plan: userPlan, company })
      fetchExperiments(userId).catch(console.error)
    }
  }, [userId, userEmail, userPlan, company])

  useEffect(() => {
    track("Page Viewed", { pageName: document.title, path: pathname })
  }, [pathname])

  return <>{children}</>
}

For the Mixpanel alternative when needing simpler event-based funnel queries with JQL (JavaScript Query Language) for ad-hoc custom reports, or when per-event pricing is more budget-friendly than Amplitude’s MTU (monthly tracked user) model — Mixpanel’s JQL gives more query flexibility while Amplitude’s built-in experiment platform and statistical analysis make it the stronger choice for teams running continuous A/B tests, see the Mixpanel guide. For the PostHog alternative when needing an open-source, self-hostable product analytics tool that covers behavioral analytics, A/B testing, feature flags, session recording, and funnels all in one — PostHog is the full-stack self-hostable alternative to both Amplitude and Mixpanel with no per-user pricing on the self-hosted tier, see the PostHog guide. The Claude Skills 360 bundle includes Amplitude skill sets covering event tracking, experiments, and revenue analytics. Start with the free tier to try behavioral analytics generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free