A webhook endpoint is a public URL that changes state in your database. Anyone who finds it can POST to it, so you need proof that each request came from the provider and wasn't modified on the way. Most providers give you that proof as an HMAC signature, and most broken integrations get one of four small details wrong.
This guide covers those details with working code for Node.js and Python. The examples use the PitchTwin header format, but the same steps apply to most signed webhooks.
What the signature is
HMAC is a keyed hash, defined in RFC 2104. The provider and you share a secret. The provider hashes the message with that secret and sends the result; you compute the same hash and compare. Without the secret, nobody can produce a matching value for a modified message.
PitchTwin sends every webhook with this header:
PitchTwin-Signature: t=1790430000,v1=5f2b…
tis a Unix timestamp in seconds.v1is the hex-encoded HMAC-SHA256 of the string${t}.${raw_body}, keyed with your webhook secret from Dashboard → API keys.
Putting the timestamp inside the signed string means an attacker can't take an old, valid request and change t to look fresh. The body is a JSON event: { "type": "generation.succeeded" | "generation.failed", "data": {...} }. Full details are in the webhooks reference.
The four rules
- Hash the raw bytes. The signature covers the exact bytes that were sent. If your framework parses the JSON and you call
JSON.stringifyon the result, key order, whitespace or number formatting can change, and valid requests start failing. - Compare in constant time. A plain
===or==returns as soon as one character differs, which can leak timing information. Usecrypto.timingSafeEqualin Node andhmac.compare_digestin Python. - Check the timestamp. Reject requests whose
tis too far from your clock. Five minutes is a common window. This limits replays of captured requests. - Parse the header defensively. A missing part, a bad number or a value of the wrong length should return
false, not throw a 500.
Node.js
crypto.timingSafeEqual throws a RangeError if the two buffers have different lengths, so check the length first.
// verify-signature.ts
import crypto from "node:crypto";
export function verifySignature(
rawBody: Buffer,
header: string,
secret: string,
toleranceSec = 300
): boolean {
const parts: Record<string, string> = {};
for (const piece of header.split(",")) {
const i = piece.indexOf("=");
if (i > 0) parts[piece.slice(0, i).trim()] = piece.slice(i + 1).trim();
}
const { t, v1 } = parts;
if (!t || !v1 || !/^\d+$/.test(t)) return false;
if (Math.abs(Date.now() / 1000 - Number(t)) > toleranceSec) return false;
const expected = crypto
.createHmac("sha256", secret)
.update(`${t}.`)
.update(rawBody)
.digest();
const given = Buffer.from(v1, "hex");
return given.length === expected.length && crypto.timingSafeEqual(given, expected);
}
Calling update() twice hashes the concatenation, so this is exactly HMAC-SHA256 of ${t}.${raw_body}. Comparing decoded bytes rather than hex strings also makes uppercase and lowercase hex equivalent.
Express
Use express.raw() on the webhook route so req.body is a Buffer. If you register express.json() globally, make sure it doesn't run before this route.
import express from "express";
import { verifySignature } from "./verify-signature";
const app = express();
app.post(
"/hooks/pitchtwin",
express.raw({ type: "application/json" }),
(req, res) => {
const ok = verifySignature(
req.body,
req.get("PitchTwin-Signature") ?? "",
process.env.PITCHTWIN_WEBHOOK_SECRET!
);
if (!ok) return res.status(400).send("invalid signature");
const event = JSON.parse(req.body.toString("utf8"));
// event.type, event.data.id, event.data.video_url …
res.sendStatus(200);
}
);
Next.js App Router
Route handlers receive a standard Request, so read the body as bytes before parsing:
// app/hooks/pitchtwin/route.ts
import { verifySignature } from "@/lib/verify-signature";
export async function POST(req: Request) {
const raw = Buffer.from(await req.arrayBuffer());
const header = req.headers.get("PitchTwin-Signature") ?? "";
if (!verifySignature(raw, header, process.env.PITCHTWIN_WEBHOOK_SECRET!)) {
return new Response("invalid signature", { status: 400 });
}
const event = JSON.parse(raw.toString("utf8"));
// handle event
return new Response("ok");
}
Python
Python's hmac module has everything you need. Pass bytes to compare_digest: with str arguments it raises TypeError on non-ASCII input.
# verify_signature.py
import hashlib
import hmac
import time
def verify_signature(raw_body: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
parts = {}
for piece in header.split(","):
key, sep, value = piece.strip().partition("=")
if sep:
parts[key] = value
t, v1 = parts.get("t"), parts.get("v1")
if not t or not v1 or not (t.isascii() and t.isdigit()):
return False
if abs(time.time() - int(t)) > tolerance:
return False
expected = hmac.new(
secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected.encode(), v1.lower().encode())
Flask
request.get_data() returns the raw body as bytes:
import json
import os
from flask import Flask, request
from verify_signature import verify_signature
app = Flask(__name__)
@app.post("/hooks/pitchtwin")
def pitchtwin_hook():
raw = request.get_data()
header = request.headers.get("PitchTwin-Signature", "")
if not verify_signature(raw, header, os.environ["PITCHTWIN_WEBHOOK_SECRET"]):
return "invalid signature", 400
event = json.loads(raw)
# handle event["type"], event["data"]
return "", 200
FastAPI
Read the body with await request.body() instead of declaring a Pydantic model parameter, which would parse it first:
import json
import os
from fastapi import FastAPI, Request, Response
from verify_signature import verify_signature
app = FastAPI()
@app.post("/hooks/pitchtwin")
async def pitchtwin_hook(request: Request):
raw = await request.body()
header = request.headers.get("PitchTwin-Signature", "")
if not verify_signature(raw, header, os.environ["PITCHTWIN_WEBHOOK_SECRET"]):
return Response("invalid signature", status_code=400)
event = json.loads(raw)
# handle event["type"], event["data"]
return Response(status_code=200)
Test it locally
You don't need a real event to test your handler. Sign a sample body yourself with openssl:
t=$(date +%s)
body='{"type":"generation.succeeded","data":{"id":"test"}}'
sig=$(printf '%s.%s' "$t" "$body" \
| openssl dgst -sha256 -hmac "$PITCHTWIN_WEBHOOK_SECRET" \
| sed 's/^.* //')
curl -i http://localhost:3000/hooks/pitchtwin \
-H "Content-Type: application/json" \
-H "PitchTwin-Signature: t=$t,v1=$sig" \
--data-raw "$body"
Then change one character in body and confirm you get a 400. Also test a missing header and a timestamp older than five minutes.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Re-serializing parsed JSON | Valid webhooks fail | Hash the raw request bytes |
=== / == compare | Possible timing leak | timingSafeEqual / compare_digest |
| No length check in Node | Bad header causes a 500 | Compare lengths first |
| Using the API key as the secret | Every signature fails | Use the webhook secret from Dashboard → API keys |
| Server clock drift | Fresh webhooks rejected | Keep the clock synced with NTP |
| Slow work before responding | Timeouts on your side | Verify, store, return 2xx, then process |
Two more notes for PitchTwin specifically. Each webhook is delivered once, so pair your endpoint with polling of GET /generations/:id for anything still pending; Async video generation with webhooks shows that pattern. And because results go straight to your endpoint, the end user only ever sees your product, which is how white-label avatar video works.
Try it
Create a free account (60 free tokens, no card), copy the webhook secret from the dashboard, and run the curl test above against your handler. The API docs list the full event payload.