posthog-webhooks-events
Implement PostHog webhook destinations, Action-triggered notifications, and event querying via the Events API and HogQL. Trigger: "posthog webhook", "posthog events API", "posthog actions", "posthog notifications", "posthog event query", "posthog HogQL".
What this skill does
# 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
```bash
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
```typescript
// 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
```bash
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
```typescript
// 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
| Issue | Cause | Solution |
|-------|-------|----------|
| Webhook not firing | No matching destination filter | Check event name matches filter exactly |
| Duplicate webhooks | Event matches multiple destinations | Narrow destination filters |
| Webhook timeout | Handler too slow | Acknowledge with 200 immediately, process async |
| HogQL query timeout | Unfiltered table scan | Add `timestamp >` filter and `LIMIT` |
| 429 on events API | Too many queries | Cache 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
- [PostHog CDP Destinations](https://posthog.com/docs/cdp/destinations)
- [PostHog Webhook Destination](https://posthog.com/docs/cdp/destinations/webhook)
- [PostHog Events API](https://posthog.com/docs/api/events)
- [HogQL Documentation](https://posthog.com/docs/sql)
## Next Steps
For deployment setup, see `posthog-deploy-integration`.
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.