posthog-common-errors

0
0
Source

Diagnose and fix PostHog common errors and exceptions. Use when encountering PostHog errors, debugging failed requests, or troubleshooting integration issues. Trigger with phrases like "posthog error", "fix posthog", "posthog not working", "debug posthog".

Install

mkdir -p .claude/skills/posthog-common-errors && curl -L -o skill.zip "https://mcp.directory/api/skills/download/5380" && unzip -o skill.zip -d .claude/skills/posthog-common-errors && rm skill.zip

Installs to .claude/skills/posthog-common-errors

About this skill

PostHog Common Errors

Overview

Diagnosis and solutions for the most common PostHog integration errors. Covers event capture failures, authentication issues, feature flag problems, identity fragmentation, and SDK initialization errors.

Prerequisites

  • PostHog SDK installed (posthog-js or posthog-node)
  • Access to browser console or server logs
  • PostHog project API key (phc_...) available

Instructions

Error 1: Events Not Appearing in Dashboard

Symptoms: posthog.capture() calls execute without error but events never show in PostHog Activity tab.

Diagnoses and fixes:

// Problem A: Not flushing in serverless/scripts
// posthog-node queues events — they're lost if process exits before flush
const posthog = new PostHog('phc_...');
posthog.capture({ distinctId: 'user-1', event: 'test' });
// FIX: Always flush before exit
await posthog.shutdown(); // or await posthog.flush()

// Problem B: Wrong API host
posthog.init('phc_...', {
  api_host: 'https://app.posthog.com', // WRONG — this is the UI
});
// FIX: Use the ingest endpoint
posthog.init('phc_...', {
  api_host: 'https://us.i.posthog.com', // CORRECT for US Cloud
  // api_host: 'https://eu.i.posthog.com', // For EU Cloud
});

// Problem C: Ad blocker blocking posthog-js requests
// FIX: Set up a reverse proxy (see posthog-sdk-patterns)
// next.config.js rewrites: /ingest/* → us.i.posthog.com/*
// Then: posthog.init('phc_...', { api_host: '/ingest' });

Error 2: Feature Flag Returns undefined or Wrong Value

// Problem: Checking flag before flags are loaded
const value = posthog.isFeatureEnabled('my-flag'); // undefined — flags not ready

// FIX: Wait for flags to load
posthog.onFeatureFlags(() => {
  const value = posthog.isFeatureEnabled('my-flag'); // Now has correct value
});

// Problem (server): No personalApiKey — falls back to remote evaluation
const ph = new PostHog('phc_...'); // Missing personalApiKey
const flag = await ph.getFeatureFlag('my-flag', 'user-1'); // Slow, may fail

// FIX: Add personalApiKey for local evaluation
const ph = new PostHog('phc_...', {
  personalApiKey: process.env.POSTHOG_PERSONAL_API_KEY, // phx_...
});
// Now evaluates locally — faster and more reliable

Error 3: 401 Unauthorized on API Calls

set -euo pipefail
# Symptom: 401 when calling admin endpoints
curl "https://app.posthog.com/api/projects/$POSTHOG_PROJECT_ID/feature_flags/" \
  -H "Authorization: Bearer phc_wrong_key_type"
# Returns: {"detail": "Authentication credentials were not provided."}

# FIX: Use Personal API Key (phx_...) for admin endpoints, not project key (phc_...)
curl "https://app.posthog.com/api/projects/$POSTHOG_PROJECT_ID/feature_flags/" \
  -H "Authorization: Bearer $POSTHOG_PERSONAL_API_KEY"  # Must be phx_...

# Check which key type you have:
echo "$POSTHOG_PERSONAL_API_KEY" | head -c 4
# phx_ = Personal API Key (correct for admin API)
# phc_ = Project API Key (only for event capture)

Error 4: 429 Rate Limited

// Symptom: HTTP 429 on analytics endpoints
// PostHog rate limits: 240 req/min and 1200 req/hour for analytics endpoints
// Feature flag local eval: 600 req/min

// FIX: Implement backoff with Retry-After header
async function postHogRequest(url: string, options: RequestInit) {
  const response = await fetch(url, options);

  if (response.status === 429) {
    const retryAfter = parseInt(response.headers.get('Retry-After') || '60');
    console.warn(`PostHog rate limited. Retrying in ${retryAfter}s`);
    await new Promise(r => setTimeout(r, retryAfter * 1000));
    return postHogRequest(url, options); // Retry
  }

  return response;
}

// FIX: Cache insight results instead of polling
let cachedInsights: any = null;
let cacheExpiry = 0;

async function getInsights() {
  if (cachedInsights && Date.now() < cacheExpiry) return cachedInsights;

  const res = await postHogRequest(
    `https://app.posthog.com/api/projects/${PROJECT_ID}/insights/trend/`,
    { headers: { Authorization: `Bearer ${PERSONAL_KEY}` } }
  );
  cachedInsights = await res.json();
  cacheExpiry = Date.now() + 300000; // Cache 5 minutes
  return cachedInsights;
}

Error 5: Identity Fragmentation (Duplicate Users)

// Problem: Same user appears as multiple persons in PostHog
// Cause: Different distinct_id on frontend vs backend

// Frontend captures with anonymous ID: "anon-abc123"
posthog.capture('page_viewed'); // distinct_id = "anon-abc123"

// Backend captures with user ID: "user-456"
serverPosthog.capture({
  distinctId: 'user-456', // Different from frontend!
  event: 'api_called',
});

// FIX: Call identify on frontend to merge anonymous → known
posthog.identify('user-456'); // Merges anon-abc123 → user-456

// FIX: Use same distinct_id on server as frontend
serverPosthog.capture({
  distinctId: 'user-456', // Same as what frontend uses after identify
  event: 'api_called',
});

Error 6: posthog-js Not Loading or Initializing

// Problem: posthog.capture is not a function
// Cause: SDK not initialized or called server-side

// FIX: Guard all browser calls
if (typeof window !== 'undefined') {
  posthog.init('phc_...', { api_host: 'https://us.i.posthog.com' });
}

// FIX: Check if initialized before capturing
if (typeof posthog.capture === 'function') {
  posthog.capture('my_event');
}

// Problem: CSP (Content Security Policy) blocking PostHog
// FIX: Add PostHog domains to your CSP header
// connect-src: https://us.i.posthog.com https://us-assets.i.posthog.com

Quick Diagnostic Commands

set -euo pipefail
# 1. Check PostHog API reachability
curl -s -o /dev/null -w "HTTP %{http_code}\n" https://us.i.posthog.com/healthz

# 2. Verify project API key works (send test event)
curl -s -X POST 'https://us.i.posthog.com/capture/' \
  -H 'Content-Type: application/json' \
  -d "{\"api_key\":\"$NEXT_PUBLIC_POSTHOG_KEY\",\"event\":\"diagnostic_test\",\"distinct_id\":\"debug\"}" | jq .

# 3. Verify personal API key works
curl -s "https://app.posthog.com/api/projects/" \
  -H "Authorization: Bearer $POSTHOG_PERSONAL_API_KEY" | jq '.[0].name'

# 4. Check installed SDK versions
npm list posthog-js posthog-node 2>/dev/null || echo "No PostHog SDK found"

# 5. Check environment variables
env | grep -i posthog | sed 's/=.*/=***/'

Error Handling

ErrorHTTP CodeCauseSolution
Events missingN/ANot flushedawait posthog.shutdown()
Auth failed401Wrong key typeUse phx_ for admin, phc_ for capture
Rate limited429Too many API callsBackoff, cache results
Flag undefinedN/AFlags not loadedUse onFeatureFlags callback
CSP blockedN/AMissing CSP entryAdd us.i.posthog.com to connect-src
Duplicate usersN/AIdentity mismatchCall posthog.identify() consistently

Output

  • Root cause identified for PostHog integration errors
  • Fix applied with verification steps
  • Diagnostic output confirming resolution

Resources

Next Steps

For comprehensive debugging, see posthog-debug-bundle.

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

6814

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

2412

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

379

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

978

performing-security-audits

jeremylongshore

This skill allows Claude to conduct comprehensive security audits of code, infrastructure, and configurations. It leverages various tools within the security-pro-pack plugin, including vulnerability scanning, compliance checking, cryptography review, and infrastructure security analysis. Use this skill when a user requests a "security audit," "vulnerability assessment," "compliance review," or any task involving identifying and mitigating security risks. It helps to ensure code and systems adhere to security best practices and compliance standards.

86

django-view-generator

jeremylongshore

Generate django view generator operations. Auto-activating skill for Backend Development. Triggers on: django view generator, django view generator Part of the Backend Development skill category. Use when working with django view generator functionality. Trigger with phrases like "django view generator", "django generator", "django".

15

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

643969

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

591705

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318398

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

339397

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

451339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.