posthog-webhooks-events

0
0
Source

Implement PostHog webhook signature validation and event handling. Use when setting up webhook endpoints, implementing signature verification, or handling PostHog event notifications securely. Trigger with phrases like "posthog webhook", "posthog events", "posthog webhook signature", "handle posthog events", "posthog notifications".

Install

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

Installs to .claude/skills/posthog-webhooks-events

About this skill

PostHog Webhooks & Events

Overview

PostHog sends webhooks via its CDP (Customer Data Platform) Destinations feature. You configure a Destination that fires when matching events are captured, sending an HTTP POST to your endpoint. This skill covers webhook destination setup, receiving and processing webhook payloads, querying events via the API, and using HogQL for custom event analysis.

Prerequisites

  • PostHog project with personal API key (phx_...)
  • HTTPS endpoint to receive webhooks
  • Events being captured in PostHog

Instructions

Step 1: Create a Webhook Destination via API

set -euo pipefail
# Create a webhook destination that fires on specific events
curl -X POST "https://app.posthog.com/api/projects/$POSTHOG_PROJECT_ID/pipeline_destinations/" \
  -H "Authorization: Bearer $POSTHOG_PERSONAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Signup Notifications",
    "description": "Send webhook when user signs up",
    "config": {
      "url": "https://your-app.com/webhooks/posthog",
      "method": "POST",
      "headers": {
        "X-Webhook-Secret": "your-webhook-secret"
      },
      "body": {
        "event": "{event}",
        "distinct_id": "{distinct_id}",
        "person": "{person}",
        "properties": "{properties}",
        "timestamp": "{timestamp}"
      }
    },
    "filters": {
      "events": [
        {"id": "user_signed_up", "type": "events"},
        {"id": "subscription_started", "type": "events"}
      ]
    }
  }'

Step 2: Receive and Process Webhooks

// api/webhooks/posthog.ts
import { NextResponse } from 'next/server';
import crypto from 'crypto';

const WEBHOOK_SECRET = process.env.POSTHOG_WEBHOOK_SECRET!;

// Verify webhook authenticity
function verifySignature(payload: string, signature: string): boolean {
  const expected = crypto.createHmac('sha256', WEBHOOK_SECRET)
    .update(payload)
    .digest('hex');
  return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
}

interface PostHogWebhookPayload {
  event: string;
  distinct_id: string;
  properties: Record<string, any>;
  person: {
    properties: Record<string, any>;
  };
  timestamp: string;
}

export async function POST(request: Request) {
  const body = await request.text();
  const signature = request.headers.get('x-webhook-secret') || '';

  // Verify webhook is from PostHog
  if (WEBHOOK_SECRET && signature !== WEBHOOK_SECRET) {
    return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
  }

  const payload: PostHogWebhookPayload = JSON.parse(body);

  // Route to handlers based on event type
  switch (payload.event) {
    case 'user_signed_up':
      await onUserSignup(payload);
      break;
    case 'subscription_started':
      await onSubscriptionStarted(payload);
      break;
    case 'subscription_canceled':
      await onSubscriptionCanceled(payload);
      break;
    default:
      console.log(`Unhandled PostHog event: ${payload.event}`);
  }

  return NextResponse.json({ received: true });
}

async function onUserSignup(payload: PostHogWebhookPayload) {
  const { distinct_id, properties, person } = payload;
  console.log(`New signup: ${distinct_id}`);

  // Sync to CRM
  await fetch('https://api.hubspot.com/contacts/v1/contact/', {
    method: 'POST',
    headers: { Authorization: `Bearer ${process.env.HUBSPOT_KEY}` },
    body: JSON.stringify({
      properties: [
        { property: 'email', value: person.properties.email },
        { property: 'posthog_id', value: distinct_id },
      ],
    }),
  });

  // Notify Slack
  await fetch(process.env.SLACK_WEBHOOK_URL!, {
    method: 'POST',
    body: JSON.stringify({
      text: `New signup: ${person.properties.email || distinct_id} (${properties.source || 'unknown'})`,
    }),
  });
}

async function onSubscriptionStarted(payload: PostHogWebhookPayload) {
  console.log(`New subscription: ${payload.distinct_id}, plan: ${payload.properties.plan}`);
}

async function onSubscriptionCanceled(payload: PostHogWebhookPayload) {
  console.log(`Cancellation: ${payload.distinct_id}`);
}

Step 3: Query Events via the API

set -euo pipefail
# List recent events by type
curl "https://app.posthog.com/api/projects/$POSTHOG_PROJECT_ID/events/?event=user_signed_up&limit=10&orderBy=-timestamp" \
  -H "Authorization: Bearer $POSTHOG_PERSONAL_API_KEY" | \
  jq '.results[] | {
    distinct_id,
    event,
    timestamp,
    properties: (.properties | {source, plan, referrer: ."$referrer"})
  }'

# Get events for a specific person
curl "https://app.posthog.com/api/projects/$POSTHOG_PROJECT_ID/events/?distinct_id=user-123&limit=20" \
  -H "Authorization: Bearer $POSTHOG_PERSONAL_API_KEY" | \
  jq '.results[] | {event, timestamp}'

Step 4: Query Events with HogQL

// Complex event analysis with HogQL (PostHog's SQL dialect)
async function queryPostHog(hogql: string) {
  const response = await fetch(
    `https://app.posthog.com/api/projects/${process.env.POSTHOG_PROJECT_ID}/query/`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${process.env.POSTHOG_PERSONAL_API_KEY}`,
      },
      body: JSON.stringify({
        query: { kind: 'HogQLQuery', query: hogql },
      }),
    }
  );
  return response.json();
}

// Example: Signup funnel analysis
const funnelData = await queryPostHog(`
  SELECT
    properties.$referrer AS referrer,
    count() AS signups,
    uniq(distinct_id) AS unique_users
  FROM events
  WHERE event = 'user_signed_up'
    AND timestamp > now() - interval 30 day
  GROUP BY referrer
  ORDER BY signups DESC
  LIMIT 20
`);

// Example: Feature adoption by plan
const adoptionData = await queryPostHog(`
  SELECT
    person.properties.plan AS plan,
    properties.feature_name AS feature,
    count() AS usage_count,
    uniq(distinct_id) AS unique_users
  FROM events
  WHERE event = 'feature_used'
    AND timestamp > now() - interval 7 day
  GROUP BY plan, feature
  ORDER BY usage_count DESC
  LIMIT 50
`);

Step 5: Set Up Slack Webhook Destination (UI)

PostHog has built-in Slack integration via Data Pipelines > Destinations:

  1. Go to Data Pipelines > Destinations > New Destination
  2. Select "Slack" or "Webhook"
  3. Configure event filters (which events trigger the notification)
  4. Set the webhook URL and message template
  5. Test with a sample event

Error Handling

IssueCauseSolution
Webhook not firingNo matching destination filterCheck event name matches filter exactly
Duplicate webhooksEvent matches multiple destinationsNarrow destination filters
Webhook timeoutHandler too slowAcknowledge with 200 immediately, process async
HogQL query timeoutUnfiltered table scanAdd timestamp > filter and LIMIT
429 on events APIToo many queriesCache results, reduce polling frequency

Output

  • Webhook destination configured for specific events
  • Express/Next.js webhook handler with event routing
  • Event queries via REST API and HogQL
  • Slack/CRM integration on user lifecycle events

Resources

Next Steps

For deployment setup, see posthog-deploy-integration.

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.

7824

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

13615

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.

3114

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.

4311

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.

109

designing-database-schemas

jeremylongshore

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

1128

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.

9521,094

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.

846846

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."

571699

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.

548492

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.

673466

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.

514280

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.