PO

posthog-webhooks-events

Instructions for setting up PostHog webhook destinations and querying events via the API.

Install

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

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

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 webhook destinations, Action-triggered notifications,
71 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Create webhook destinations via API
  • Verify webhook signature authenticity
  • Route events to specific handlers
  • Query event data using HogQL

How it works

Configures pipeline destinations to push event data to a secure endpoint, which then verifies the signature and routes the payload to appropriate business logic.

Inputs & outputs

You give it
Incoming HTTP POST webhook payload
You get back
Processed event action or query result

When to use posthog-webhooks-events

  • Setup webhook destinations for specific events
  • Verify incoming webhook signatures
  • Query PostHog event data via API
  • Use HogQL for custom data analysis

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.

When not to use it

  • Do not process heavy logic synchronously in webhook handlers

Prerequisites

Personal API key (phx_...)HTTPS endpointCaptured events

Limitations

  • Webhook handlers must acknowledge with 200 immediately to avoid timeouts
  • Event names must match destination filters exactly

How it compares

Provides a secure, verified integration path for real-time events compared to manual polling or unauthenticated endpoints.

Compared to similar skills

posthog-webhooks-events side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
posthog-webhooks-events (this skill)127dCautionIntermediate
windsurf-mcp-integration12moReviewAdvanced
create-mcp-server05moNo flagsIntermediate
mcp-builder1363moReviewAdvanced

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

You might also like

windsurf-mcp-integration

jeremylongshore

Manage integrate MCP servers with Windsurf for extended capabilities. Activate when users mention "mcp integration", "model context protocol", "external tools", "mcp server", or "cascade tools". Handles MCP server configuration and integration. Use when working with windsurf mcp integration functionality. Trigger with phrases like "windsurf mcp integration", "windsurf integration", "windsurf".

14

create-mcp-server

appliedcognetics

Scaffold a local MCP server with synthetic data for agentic system development. Use when creating a new data source, building tool endpoints, or generating test data for agents to consume.

00

mcp-builder

anthropics

Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).

136215

telegram-bot-builder

davila7

Expert in building Telegram bots that solve real problems - from simple automation to complex AI-powered bots. Covers bot architecture, the Telegram Bot API, user experience, monetization strategies, and scaling bots to thousands of users. Use when: telegram bot, bot api, telegram automation, chat bot telegram, tg bot.

106130

clawhub

openclaw

Use the ClawHub CLI to search, install, update, and publish agent skills from clawhub.com. Use when you need to fetch new skills on the fly, sync installed skills to latest or a specific version, or publish new/updated skill folders with the npm-installed clawhub CLI.

25151

n8n-expression-syntax

czlonkowski

Validate n8n expression syntax and fix common errors. Use when writing n8n expressions, using {{}} syntax, accessing $json/$node variables, troubleshooting expression errors, or working with webhook data in workflows.

6111

Search skills

Search the agent skills registry