Verify PostHog webhooks

Signing is optional on PostHog's HTTP Webhook destination. Set a Signing secret and each request carries webhook-id, webhook-timestamp and webhook-signature headers that follow the Standard Webhooks spec, which the standardwebhooks libraries can verify. Without one PostHog sends no signature headers, so you can only check a token you set in Secret headers. PostHog's docs page doesn't cover signing, so the details here come from its open-source destination code.

These pages cover events PostHog sends out to your endpoint. To send webhooks from other tools into PostHog, see its incoming webhooks source.

The facts

Signature header
webhook-signature

Not every delivery is signed: check your setup.

Scheme
HMAC-SHA256, base64
Signed material
{webhook-id}.{webhook-timestamp}.{raw body}

The two header values and the body as sent, joined with literal dots. The key is the secret base64-decoded, not the secret string.

Send timestamp
webhook-timestamp
What to build
Recompute the HMAC over id, timestamp and raw body, and compare
Key
shared secret

PostHog webhook secret

PostHog doesn't issue a secret. You generate one in Standard Webhooks form and paste it into the destination's Signing secret input. Keep it in an environment variable, not in source code.

  • Generate one with echo "whsec_$(openssl rand -base64 32)".
  • It must be base64, with or without the whsec_ prefix, and decode to at least 24 bytes. Otherwise PostHog refuses to send the request and logs why.
  • Keep the whsec_ prefix and paste the same string into PostHog and your receiver. A receiver can treat an unprefixed secret as plain text, which gives it a different key from PostHog's.
  • Each destination has its own secret. PostHog has no separate test and live secrets, and documents no rotation.
  • PostHog encrypts secret inputs and doesn't show them again, so keep your own copy.

Source: PostHog docs ↗

Code

express/src/index.js
javascript
require('dotenv').config({ quiet: true });
const express = require('express');
const { Webhook } = require('standardwebhooks');

const app = express();

// Verify the request and return the parsed JSON body.
// PostHog signs `${webhook-id}.${webhook-timestamp}.${raw body}` with HMAC-SHA256
// (Standard Webhooks). The library enforces a fixed 5-minute timestamp window.
function verifyPostHog(rawBody, headers, secret) {
  const wh = new Webhook(secret); // strips optional whsec_, base64-decodes
  return wh.verify(rawBody, {
    'webhook-id': headers['webhook-id'],
    'webhook-timestamp': headers['webhook-timestamp'],
    'webhook-signature': headers['webhook-signature'],
  });
}

// CRITICAL: raw body for verification. type '*/*' so any content type verifies.
app.post('/webhooks/posthog', express.raw({ type: '*/*' }), (req, res) => {
  const secret = process.env.POSTHOG_WEBHOOK_SECRET;
  if (!secret) {
    return res.status(500).json({ error: 'POSTHOG_WEBHOOK_SECRET is not set' });
  }

  if (!req.headers['webhook-id'] || !req.headers['webhook-timestamp'] || !req.headers['webhook-signature']) {
    return res.status(400).json({ error: 'Missing webhook-id, webhook-timestamp or webhook-signature header' });
  }

  const rawBody = Buffer.isBuffer(req.body) ? req.body.toString('utf8') : '';

  let payload;
  try {
    payload = verifyPostHog(rawBody, req.headers, secret);
  } catch (err) {
    console.error('PostHog signature verification failed:', err.message);
    return res.status(400).json({ error: 'Invalid signature' });
  }

  // The body is whatever the destination template sends. The default is
  // { event: { event, uuid, distinct_id, properties, timestamp, ... }, person: {...} }
  const event = payload && payload.event;
  const name = event && event.event;

  switch (name) {
    case '$pageview':
      console.log('Pageview:', event.distinct_id, event.properties && event.properties.$current_url);
      break;
    case '$identify':
      console.log('Identify:', event.distinct_id);
      break;
    case '$autocapture':
      console.log('Autocapture:', event.distinct_id);
      break;
    default:
      // Custom events arrive under their own names, e.g. "signed_up"
      console.log('Event:', name);
  }

  res.status(200).json({ received: true });
});

app.get('/health', (req, res) => res.json({ status: 'ok' }));

if (require.main === module) {
  const port = process.env.PORT || 3000;
  app.listen(port, () => console.log(`PostHog webhook server listening on http://localhost:${port}`));
}

module.exports = app;
nextjs/app/webhooks/posthog/route.ts
typescript
import { NextRequest, NextResponse } from 'next/server';
import { Webhook } from 'standardwebhooks';

export async function POST(request: NextRequest) {
  const secret = process.env.POSTHOG_WEBHOOK_SECRET;
  if (!secret) {
    return NextResponse.json({ error: 'POSTHOG_WEBHOOK_SECRET is not set' }, { status: 500 });
  }

  const id = request.headers.get('webhook-id');
  const timestamp = request.headers.get('webhook-timestamp');
  const signature = request.headers.get('webhook-signature');
  if (!id || !timestamp || !signature) {
    return NextResponse.json(
      { error: 'Missing webhook-id, webhook-timestamp or webhook-signature header' },
      { status: 400 }
    );
  }

  // CRITICAL: read the raw body as text; do not parse JSON before verifying
  const rawBody = await request.text();

  let payload: any;
  try {
    // PostHog signs `${id}.${timestamp}.${rawBody}` with HMAC-SHA256 (Standard Webhooks).
    // The library enforces a fixed 5-minute timestamp window.
    payload = new Webhook(secret).verify(rawBody, {
      'webhook-id': id,
      'webhook-timestamp': timestamp,
      'webhook-signature': signature,
    });
  } catch (err) {
    console.error('PostHog signature verification failed:', (err as Error).message);
    return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
  }

  // Default body: { event: { event, uuid, distinct_id, properties, timestamp, ... }, person: {...} }
  const event = payload?.event;
  switch (event?.event) {
    case '$pageview':
      console.log('Pageview:', event.distinct_id, event.properties?.$current_url);
      break;
    case '$identify':
      console.log('Identify:', event.distinct_id);
      break;
    case '$autocapture':
      console.log('Autocapture:', event.distinct_id);
      break;
    default:
      // Custom events arrive under their own names, e.g. "signed_up"
      console.log('Event:', event?.event);
  }

  return NextResponse.json({ received: true });
}
fastapi/main.py
python
import os

from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request
from standardwebhooks.webhooks import Webhook, WebhookVerificationError

load_dotenv()

app = FastAPI()


@app.post("/webhooks/posthog")
async def posthog_webhook(request: Request):
    secret = os.environ.get("POSTHOG_WEBHOOK_SECRET")
    if not secret:
        raise HTTPException(status_code=500, detail="POSTHOG_WEBHOOK_SECRET is not set")

    headers = {
        "webhook-id": request.headers.get("webhook-id"),
        "webhook-timestamp": request.headers.get("webhook-timestamp"),
        "webhook-signature": request.headers.get("webhook-signature"),
    }
    if not all(headers.values()):
        raise HTTPException(
            status_code=400,
            detail="Missing webhook-id, webhook-timestamp or webhook-signature header",
        )

    # CRITICAL: verify against the raw body, not re-serialized JSON
    raw_body = await request.body()

    try:
        # HMAC-SHA256 over "{id}.{timestamp}.{body}" (Standard Webhooks).
        # The library enforces a fixed 5-minute timestamp window.
        payload = Webhook(secret).verify(raw_body, headers)
    except WebhookVerificationError:
        raise HTTPException(status_code=400, detail="Invalid signature")

    # Default body: {"event": {"event", "uuid", "distinct_id", "properties", ...}, "person": {...}}
    event = (payload or {}).get("event") or {}
    name = event.get("event")

    if name == "$pageview":
        print("Pageview:", event.get("distinct_id"), (event.get("properties") or {}).get("$current_url"))
    elif name == "$identify":
        print("Identify:", event.get("distinct_id"))
    elif name == "$autocapture":
        print("Autocapture:", event.get("distinct_id"))
    else:
        # Custom events arrive under their own names, e.g. "signed_up"
        print("Event:", name)

    return {"received": True}


@app.get("/health")
async def health():
    return {"status": "ok"}

From hookdeck/webhook-skills ↗

Or install the PostHog webhooks skill:

npx skills add hookdeck/webhook-skills --skill posthog-webhooks

Common failures

Body parsed before verification

The signature covers the bytes PostHog sent. Verify against the raw request body, before any JSON parsing.

Secret used as a plain string

The key is the secret base64-decoded after removing any whsec_ prefix. A receiver that treats an unprefixed secret as plain text gets a different key, so keep the prefix and use the same string on both sides.

Timestamp too old on a replay

PostHog signs each of its own attempts with a fresh timestamp, but the standardwebhooks libraries reject anything more than 5 minutes old, and a queue's later retry or replay keeps the original headers. Behind a queue, use a verifier whose window you can widen or turn off, and deduplicate on webhook-id.

Destination set to GET

With GET, PostHog signs the templated body but doesn't send it, so your receiver has nothing to match. Keep the method as POST.

From Hookdeck's PostHog guide

Let Event Gateway verify PostHog signatures.

Event Gateway verifies the signature on each PostHog delivery before it reaches your service, then queues it and retries failures on your schedule.

Not affiliated with PostHog. Facts are compiled from public sources and linked inline.