PO

posthog-core-workflow-b

A guide to using PostHog for feature flag management, multivariate testing, and cohort-based analysis.

Install

mkdir -p .claude/skills/posthog-core-workflow-b && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/2400" && unzip -o skill.zip -d .claude/skills/posthog-core-workflow-b && rm skill.zip

Installs to .claude/skills/posthog-core-workflow-b

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Implement PostHog feature flags, A/B experiments, and cohort management.
72 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Evaluate boolean feature flags in the browser.
  • Evaluate multivariate feature flags to get variant names.
  • Retrieve feature flag payloads containing JSON data.
  • Evaluate feature flags server-side using posthog-node.
  • Create boolean feature flags with percentage rollout via API.
  • Set up A/B experiments by tracking exposure and goal metrics.

How it works

This skill provides instructions and code examples for managing feature flags and experiments in PostHog, covering client-side and server-side evaluation, API-based flag creation, and experiment setup.

Inputs & outputs

You give it
User ID, feature flag key, person properties, group properties
You get back
Feature flag status (enabled/disabled), variant name, flag payload, experiment results

When to use posthog-core-workflow-b

  • Implement feature flags for gradual rollouts
  • Set up A/B test experiment evaluation
  • Create cohorts via PostHog API
  • Manage multivariate feature configurations

About this skill

PostHog Core Workflow B — Feature Flags & Experiments

Overview

Feature flag management, A/B experiment evaluation, and cohort analysis with PostHog. Covers boolean and multivariate flags, local evaluation for performance, experiment setup and statistical significance, and cohort creation via the API.

Prerequisites

  • Completed posthog-install-auth setup
  • Familiarity with posthog-core-workflow-a (event capture)
  • Personal API key (phx_...) for flag management API

Instructions

Step 1: Evaluate Feature Flags (Browser)

import posthog from 'posthog-js';

// Boolean flag
if (posthog.isFeatureEnabled('new-checkout-flow')) {
  renderNewCheckout();
} else {
  renderLegacyCheckout();
}

// Multivariate flag (returns string variant name)
const variant = posthog.getFeatureFlag('pricing-page-experiment');
switch (variant) {
  case 'control':
    renderOriginalPricing();
    break;
  case 'annual-first':
    renderAnnualFirstPricing();
    break;
  case 'social-proof':
    renderSocialProofPricing();
    break;
  default:
    renderOriginalPricing(); // Fallback if flag not loaded yet
}

// Get flag payload (JSON data attached to a flag variant)
const payload = posthog.getFeatureFlagPayload('banner-config');
// payload: { text: "Spring sale!", color: "#ff6b35", discount: 20 }

// React: Wait for flags to load before rendering
posthog.onFeatureFlags(() => {
  // Flags are now loaded and ready
  const enabled = posthog.isFeatureEnabled('new-feature');
  setFeatureEnabled(enabled ?? false);
});

Step 2: Evaluate Feature Flags (Server — posthog-node)

import { PostHog } from 'posthog-node';

const posthog = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
  host: 'https://us.i.posthog.com',
  // Personal API key enables local evaluation (no network call per flag check)
  personalApiKey: process.env.POSTHOG_PERSONAL_API_KEY,
});

// Single flag evaluation
async function checkFlag(userId: string): Promise<boolean> {
  const enabled = await posthog.isFeatureEnabled('new-api-version', userId);
  return enabled ?? false;
}

// Multivariate flag
async function getVariant(userId: string): Promise<string> {
  const variant = await posthog.getFeatureFlag('onboarding-experiment', userId, {
    personProperties: { plan: 'pro', country: 'US' },
  });
  return (variant as string) || 'control';
}

// Get ALL flags for a user at once (one network call)
async function getUserFlags(userId: string) {
  const flags = await posthog.getAllFlags(userId, {
    personProperties: { plan: 'enterprise' },
    groupProperties: { company: { name: 'Acme' } },
  });
  // flags: { 'new-checkout': true, 'pricing-experiment': 'variant-a', ... }
  return flags;
}

// Get all flags with their payloads
async function getFlagsAndPayloads(userId: string) {
  const result = await posthog.getAllFlagsAndPayloads(userId);
  // result.featureFlags: { 'banner': true }
  // result.featureFlagPayloads: { 'banner': { text: 'Sale!' } }
  return result;
}

Step 3: Create Feature Flags via API

set -euo pipefail
# Create a boolean feature flag with percentage rollout
curl -X POST "https://app.posthog.com/api/projects/$POSTHOG_PROJECT_ID/feature_flags/" \
  -H "Authorization: Bearer $POSTHOG_PERSONAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "key": "new-dashboard-v2",
    "name": "New Dashboard V2",
    "active": true,
    "filters": {
      "groups": [{
        "rollout_percentage": 25,
        "properties": []
      }]
    }
  }'

# Create a multivariate flag for A/B testing
curl -X POST "https://app.posthog.com/api/projects/$POSTHOG_PROJECT_ID/feature_flags/" \
  -H "Authorization: Bearer $POSTHOG_PERSONAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "key": "checkout-experiment",
    "name": "Checkout Flow Experiment",
    "active": true,
    "filters": {
      "multivariate": {
        "variants": [
          {"key": "control", "rollout_percentage": 50},
          {"key": "streamlined", "rollout_percentage": 50}
        ]
      },
      "groups": [{"rollout_percentage": 100, "properties": []}]
    }
  }'

Step 4: Set Up an Experiment

// Track experiment exposure and goal metrics
async function runExperiment(userId: string) {
  const posthog = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!);

  // PostHog automatically tracks $feature_flag_called when you evaluate
  const variant = await posthog.getFeatureFlag('checkout-experiment', userId);

  // Track the goal metric
  posthog.capture({
    distinctId: userId,
    event: 'purchase_completed',
    properties: {
      variant,
      order_value: 49.99,
      // PostHog will attribute this to the experiment automatically
    },
  });

  await posthog.flush();
  return variant;
}

Step 5: Query Experiment Results via API

set -euo pipefail
# List experiments and their status
curl "https://app.posthog.com/api/projects/$POSTHOG_PROJECT_ID/experiments/" \
  -H "Authorization: Bearer $POSTHOG_PERSONAL_API_KEY" | \
  jq '.results[] | {id, name, start_date, end_date, feature_flag_key}'

# Get experiment results
curl "https://app.posthog.com/api/projects/$POSTHOG_PROJECT_ID/experiments/EXPERIMENT_ID/results/" \
  -H "Authorization: Bearer $POSTHOG_PERSONAL_API_KEY" | \
  jq '{
    variants: [.result.variants[] | {key, count, conversion_rate: .absolute_exposure}],
    significance: .result.significance_code,
    probability: .result.probability
  }'

Step 6: Manage Cohorts via API

set -euo pipefail
# Create a behavioral cohort (users who signed up in last 30 days)
curl -X POST "https://app.posthog.com/api/projects/$POSTHOG_PROJECT_ID/cohorts/" \
  -H "Authorization: Bearer $POSTHOG_PERSONAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Recent Signups (30d)",
    "is_calculating": true,
    "filters": {
      "properties": {
        "type": "AND",
        "values": [{
          "type": "AND",
          "values": [{
            "key": "user_signed_up",
            "type": "behavioral",
            "value": "performed_event",
            "time_value": 30,
            "time_interval": "day"
          }]
        }]
      }
    }
  }'

# List cohorts
curl "https://app.posthog.com/api/projects/$POSTHOG_PROJECT_ID/cohorts/" \
  -H "Authorization: Bearer $POSTHOG_PERSONAL_API_KEY" | \
  jq '.results[] | {id, name, count, is_calculating}'

Error Handling

ErrorCauseSolution
Flag always returns undefinedFlags not loaded yetUse posthog.onFeatureFlags() callback
Flag returns default on serverNo personalApiKey setAdd personal API key for local evaluation
Experiment not trackingGoal event name mismatchVerify event name matches experiment config
Cohort stuck is_calculatingLarge datasetWait for calculation; check PostHog status
getAllFlags slowNo local evaluationSet personalApiKey in PostHog constructor

Output

  • Feature flag evaluation (boolean and multivariate)
  • Server-side local evaluation for low-latency flag checks
  • A/B experiment setup with goal metric tracking
  • Cohort creation and management via API
  • Experiment results with statistical significance

Resources

Next Steps

For common errors, see posthog-common-errors.

When not to use it

  • When PostHog installation and authentication are not completed.
  • When event capture is not configured via posthog-core-workflow-a.

Prerequisites

Completed `posthog-install-auth` setupFamiliarity with `posthog-core-workflow-a` (event capture)Personal API key (`phx_...`) for flag management API

Limitations

  • Flags may return undefined if not loaded yet.
  • Server-side flags may return default without a personal API key.
  • Experiments may not track if goal event name mismatches configuration.

How it compares

This skill details specific PostHog API calls and SDK usage for feature flags and experiments, offering a direct implementation guide compared to general feature flagging concepts.

Compared to similar skills

posthog-core-workflow-b side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
posthog-core-workflow-b (this skill)226dCautionIntermediate
pdf-processing-pro179moReviewIntermediate
python-repl64moReviewBeginner
math-router67moReviewBeginner

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

Search skills

Search the agent skills registry