---

title: Verify a webhook
description: Check the webhook-id, webhook-timestamp and webhook-signature headers of a knownprint delivery, with the exact algorithm, a test vector and complete receivers in Node, Python and Go.
---

Anyone who learns your webhook URL can send it a request. Before your endpoint acts on a delivery, it must prove that knownprint sent it, that the body was not changed on the way, and that it is recent. Every delivery carries three headers for that, and checking them takes a few lines of code.

knownprint signs deliveries with the Standard Webhooks scheme: HMAC-SHA256 over the delivery id, the timestamp and the exact body, keyed with your webhook's secret. This page gives the algorithm, a test vector, and complete receivers you can paste. [Webhooks](/webhooks) explains what the deliveries contain.

## The headers

| Header              | Example                                           | Meaning                                                                                           |
| ------------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| `webhook-id`        | `dl_v7k75veqcqpzq4kzfy4w6cc7zu`                   | The delivery id, equal to the envelope's `id`. The same on every retry and replay                 |
| `webhook-timestamp` | `1796212800`                                      | When this attempt was signed, in Unix seconds (decimal digits)                                    |
| `webhook-signature` | `v1,t+4gKPxHirwnvUqnS3VGPSoXnp91NBCiMZ7gYYgKX+E=` | One or more signatures separated by single spaces, each a version tag, a comma and a base64 value |

Each attempt is signed when it is made, so a retry has a new timestamp and a new signature, with the same `webhook-id` and the same body.

## The algorithm

You need the secret returned when the webhook was created: `whsec_` followed by 32 base64 characters.

1. **Read the headers.** If `webhook-id`, `webhook-timestamp` or `webhook-signature` is missing or empty, reject the request.
2. **Check the timestamp.** It must be a whole number of seconds, and no more than **300 seconds** (5 minutes) away from your server's clock, earlier or later. Otherwise reject the request: it is a replay of an old delivery or your clock is wrong.
3. **Derive the key.** Remove the `whsec_` prefix from the secret and base64-decode the rest (standard alphabet, with padding). The result is 24 bytes. The key is these bytes, not the secret's text.
4. **Build the signed content.** Concatenate the `webhook-id` value, a full stop, the `webhook-timestamp` value, a full stop, and the request body exactly as received:

   ```text
   {webhook-id}.{webhook-timestamp}.{raw body}
   ```

5. **Compute the expected signature.** HMAC-SHA256 of the signed content under the key, 32 bytes.
6. **Compare.** Split `webhook-signature` on spaces. For each entry that starts with `v1,`, base64-decode what follows the comma and compare it with the expected 32 bytes using a constant-time comparison. Ignore entries with another version tag. If any `v1` entry matches, the delivery is genuine; if none does, reject it.
7. **Parse the body.** Only now parse the body as JSON and act on it.

Answer a rejected request with `400` or `401` and do nothing else. knownprint treats any answer other than `2xx` as a failed attempt and retries it on the [schedule](/webhooks#delivery-and-retries), so a delivery you reject by mistake (for example, after a deployment with the wrong secret) is tried again and can be [replayed](/webhooks#replay-a-delivery) once you fix it.

:::warning Use a constant-time comparison
Compare signatures with `crypto.timingSafeEqual` (Node), `hmac.compare_digest` (Python) or `hmac.Equal` (Go), never with `==` on strings. An ordinary comparison stops at the first differing byte, and the time it takes can leak the expected signature.
:::

## The raw body

The signature covers the exact bytes knownprint sent. If you parse the JSON first and serialise it again, whitespace, key order, number formatting and character escapes can all change, and a genuine delivery will fail to verify. Always verify against the raw body, and parse it only afterwards.

Most frameworks parse JSON before your handler runs. Here is how to get the raw bytes in the common ones:

| Framework                           | Raw body                                                                                                                                  |
| ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| Express                             | Mount `express.raw({ type: 'application/json' })` on the webhook route, before any global `express.json()`; `req.body` is then a `Buffer` |
| Fastify                             | Register the route in its own plugin with a buffer parser for `application/json` (example below)                                          |
| Next.js route handler               | `Buffer.from(await request.arrayBuffer())`; do not call `request.json()` first                                                            |
| Hono, Cloudflare Workers, Deno, Bun | `new Uint8Array(await request.arrayBuffer())`                                                                                             |
| Flask                               | `request.get_data()`                                                                                                                      |
| Django                              | `request.body`                                                                                                                            |
| FastAPI, Starlette                  | `await request.body()`                                                                                                                    |
| Go `net/http`                       | `io.ReadAll(r.Body)`                                                                                                                      |

The same applies to anything in front of your application. A proxy, API gateway or serverless platform that re-encodes the body, or one that base64-encodes it for your function (decode it first), changes the bytes you verify.

## Test vector

Use these values to test your implementation without waiting for a delivery. The secret is a made-up example.

| Input                        | Value                                             |
| ---------------------------- | ------------------------------------------------- |
| Secret                       | `whsec_dGVzdC1rZXktbm90LWEtcmVhbC1vbmUh`          |
| `webhook-id`                 | `dl_v7k75veqcqpzq4kzfy4w6cc7zu`                   |
| `webhook-timestamp`          | `1796212800`                                      |
| Body                         | the single line below, with no trailing newline   |
| Expected `webhook-signature` | `v1,t+4gKPxHirwnvUqnS3VGPSoXnp91NBCiMZ7gYYgKX+E=` |

```json title="body"
{
  "created_at": "2026-12-02T12:00:00.000Z",
  "data": { "webhook_id": "wh_amg7qtxufogaunw7qawsqrgoxb" },
  "environment_id": "env_wczpaxppqdzxap2fhelv6asokc",
  "id": "dl_v7k75veqcqpzq4kzfy4w6cc7zu",
  "type": "webhook.test",
  "v": 1,
  "visitor_id": null
}
```

The timestamp is fixed, so pass your function a "now" of `1796212800` when you test with it; with the real clock, the timestamp check rejects it. A single added newline at the end of the body changes the signature: that is the raw body pitfall in one character.

For an end-to-end check against your deployed endpoint, send a real test delivery with [`POST /v1/webhooks/{id}/test`](/api/webhooks#post-v1-webhooks-id-test) and look at its result in the [deliveries log](/webhooks#the-deliveries-log).

## Node

This uses only `node:crypto` and takes the body as a `Buffer` or any `Uint8Array`. Node lowercases incoming header names, so `req.headers['webhook-id']` works as written.

```js title="verify-knownprint.js"
import crypto from 'node:crypto';

const TOLERANCE_SECONDS = 300;

export class WebhookVerificationError extends Error {}

/**
 * Verifies a knownprint delivery and returns its parsed envelope.
 * headers: the request headers with lower-case names (Node's req.headers).
 * rawBody: the exact bytes received, as a Buffer or Uint8Array.
 * secret: the whsec_ secret returned when the webhook was created.
 */
export function verifyKnownprintWebhook(
  headers,
  rawBody,
  secret,
  nowSeconds = Math.floor(Date.now() / 1000),
) {
  const id = headers['webhook-id'];
  const timestamp = headers['webhook-timestamp'];
  const signatures = headers['webhook-signature'];
  if (typeof id !== 'string' || typeof timestamp !== 'string' || typeof signatures !== 'string') {
    throw new WebhookVerificationError('missing webhook headers');
  }
  if (!/^[0-9]+$/.test(timestamp) || Math.abs(nowSeconds - Number(timestamp)) > TOLERANCE_SECONDS) {
    throw new WebhookVerificationError('timestamp outside the tolerance');
  }
  if (!secret.startsWith('whsec_')) throw new TypeError('not a whsec_ secret');
  const key = Buffer.from(secret.slice('whsec_'.length), 'base64');
  const expected = crypto
    .createHmac('sha256', key)
    .update(`${id}.${timestamp}.`, 'utf8')
    .update(rawBody)
    .digest();
  let matched = false;
  for (const entry of signatures.split(' ')) {
    if (!entry.startsWith('v1,')) continue;
    const candidate = Buffer.from(entry.slice(3), 'base64');
    if (candidate.length === expected.length && crypto.timingSafeEqual(candidate, expected)) {
      matched = true;
    }
  }
  if (!matched) throw new WebhookVerificationError('no matching signature');
  return JSON.parse(new TextDecoder().decode(rawBody));
}
```

:::tabs
```js title="Express"
import express from 'express';
import { verifyKnownprintWebhook, WebhookVerificationError } from './verify-knownprint.js';

const app = express();

// The raw parser on this route only, registered before any app-wide express.json().
app.post('/webhooks/knownprint', express.raw({ type: 'application/json' }), (req, res) => {
  let envelope;
  try {
    envelope = verifyKnownprintWebhook(
      req.headers,
      req.body,
      process.env.KNOWNPRINT_WEBHOOK_SECRET,
    );
  } catch (err) {
    if (err instanceof WebhookVerificationError) return res.status(400).end();
    throw err;
  }
  queue.push(envelope); // your own queue: do the work after answering
  res.status(204).end();
});

app.use(express.json()); // the rest of your API

app.listen(3000);
```

```js title="Fastify"
import Fastify from 'fastify';
import { verifyKnownprintWebhook, WebhookVerificationError } from './verify-knownprint.js';

const fastify = Fastify();

// A plugin scope of its own, so the buffer parser applies to this route only.
fastify.register(async (scope) => {
  scope.addContentTypeParser('application/json', { parseAs: 'buffer' }, (_request, body, done) => {
    done(null, body);
  });

  scope.post('/webhooks/knownprint', async (request, reply) => {
    let envelope;
    try {
      envelope = verifyKnownprintWebhook(
        request.headers,
        request.body,
        process.env.KNOWNPRINT_WEBHOOK_SECRET,
      );
    } catch (err) {
      if (err instanceof WebhookVerificationError) return reply.code(400).send();
      throw err;
    }
    queue.push(envelope);
    return reply.code(204).send();
  });
});

await fastify.listen({ port: 3000 });
```

```ts title="Next.js"
// app/api/webhooks/knownprint/route.ts
import { verifyKnownprintWebhook, WebhookVerificationError } from '@/lib/verify-knownprint';

export async function POST(request: Request) {
  const rawBody = Buffer.from(await request.arrayBuffer());
  const headers = Object.fromEntries(request.headers); // header names come lower case
  let envelope;
  try {
    envelope = verifyKnownprintWebhook(headers, rawBody, process.env.KNOWNPRINT_WEBHOOK_SECRET!);
  } catch (err) {
    if (err instanceof WebhookVerificationError) return new Response(null, { status: 400 });
    throw err;
  }
  await queue.push(envelope);
  return new Response(null, { status: 204 });
}
```
:::

`queue` stands for whatever your application uses to process work after answering. [Ordering and duplicates](/webhooks#ordering-and-duplicates) shows a handler that deduplicates on `webhook-id`.

## Python

Standard library only, Python 3.10 or later. Flask, Django and Starlette all expose headers as a case-insensitive mapping, which `headers.get("webhook-id")` relies on.

```python title="verify_knownprint.py"
import base64
import hashlib
import hmac
import json
import re
import time

TOLERANCE_SECONDS = 300


class WebhookVerificationError(Exception):
    pass


def verify_knownprint_webhook(headers, raw_body: bytes, secret: str, now: int | None = None) -> dict:
    """Verifies a knownprint delivery and returns its parsed envelope.

    headers: a case-insensitive mapping (Flask, Django and Starlette all give one).
    raw_body: the exact bytes received.
    secret: the whsec_ secret returned when the webhook was created.
    """
    msg_id = headers.get("webhook-id")
    timestamp = headers.get("webhook-timestamp")
    signatures = headers.get("webhook-signature")
    if not msg_id or not timestamp or not signatures:
        raise WebhookVerificationError("missing webhook headers")
    if not re.fullmatch(r"[0-9]+", timestamp):
        raise WebhookVerificationError("malformed timestamp")
    now = int(time.time()) if now is None else now
    if abs(now - int(timestamp)) > TOLERANCE_SECONDS:
        raise WebhookVerificationError("timestamp outside the tolerance")
    if not secret.startswith("whsec_"):
        raise ValueError("not a whsec_ secret")
    key = base64.b64decode(secret[len("whsec_"):])
    signed = f"{msg_id}.{timestamp}.".encode() + raw_body
    expected = hmac.new(key, signed, hashlib.sha256).digest()
    matched = False
    for entry in signatures.split(" "):
        version, _, encoded = entry.partition(",")
        if version != "v1":
            continue
        try:
            candidate = base64.b64decode(encoded, validate=True)
        except ValueError:
            continue
        if hmac.compare_digest(candidate, expected):
            matched = True
    if not matched:
        raise WebhookVerificationError("no matching signature")
    return json.loads(raw_body)
```

:::tabs
```python title="Flask"
import os

from flask import Flask, abort, request

from verify_knownprint import WebhookVerificationError, verify_knownprint_webhook

app = Flask(__name__)


@app.post("/webhooks/knownprint")
def knownprint_webhook():
    try:
        envelope = verify_knownprint_webhook(
            request.headers, request.get_data(), os.environ["KNOWNPRINT_WEBHOOK_SECRET"]
        )
    except WebhookVerificationError:
        abort(400)
    enqueue(envelope)  # your own queue: do the work after answering
    return "", 204
```

```python title="FastAPI"
import os

from fastapi import FastAPI, HTTPException, Request, Response

from verify_knownprint import WebhookVerificationError, verify_knownprint_webhook

app = FastAPI()


@app.post("/webhooks/knownprint")
async def knownprint_webhook(request: Request):
    try:
        envelope = verify_knownprint_webhook(
            request.headers, await request.body(), os.environ["KNOWNPRINT_WEBHOOK_SECRET"]
        )
    except WebhookVerificationError:
        raise HTTPException(status_code=400)
    await enqueue(envelope)
    return Response(status_code=204)
```

```python title="Django"
import os

from django.http import HttpResponse, HttpResponseBadRequest
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from .verify_knownprint import WebhookVerificationError, verify_knownprint_webhook


@csrf_exempt  # the signature, not a CSRF token, authenticates this route
@require_POST
def knownprint_webhook(request):
    try:
        envelope = verify_knownprint_webhook(
            request.headers, request.body, os.environ["KNOWNPRINT_WEBHOOK_SECRET"]
        )
    except WebhookVerificationError:
        return HttpResponseBadRequest()
    enqueue(envelope)
    return HttpResponse(status=204)
```
:::

## Go

Standard library only. `http.Header.Get` matches header names in any case.

```go title="main.go"
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"errors"
	"io"
	"log"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

const toleranceSeconds = 300

var ErrVerification = errors.New("knownprint: webhook verification failed")

// Envelope is a knownprint delivery in the standard format.
type Envelope struct {
	V             int             `json:"v"`
	ID            string          `json:"id"`
	Type          string          `json:"type"`
	CreatedAt     time.Time       `json:"created_at"`
	EnvironmentID string          `json:"environment_id"`
	VisitorID     *string         `json:"visitor_id"`
	Data          json.RawMessage `json:"data"`
}

// VerifyWebhook checks a delivery's signature headers against the exact body received
// and returns the parsed envelope.
func VerifyWebhook(header http.Header, body []byte, secret string, now time.Time) (*Envelope, error) {
	id := header.Get("webhook-id")
	stamp := header.Get("webhook-timestamp")
	signatures := header.Get("webhook-signature")
	if id == "" || stamp == "" || signatures == "" {
		return nil, ErrVerification
	}
	for _, c := range stamp {
		if c < '0' || c > '9' {
			return nil, ErrVerification
		}
	}
	ts, err := strconv.ParseInt(stamp, 10, 64)
	if err != nil {
		return nil, ErrVerification
	}
	if d := now.Unix() - ts; d > toleranceSeconds || d < -toleranceSeconds {
		return nil, ErrVerification
	}
	encoded, ok := strings.CutPrefix(secret, "whsec_")
	if !ok {
		return nil, errors.New("knownprint: not a whsec_ secret")
	}
	key, err := base64.StdEncoding.DecodeString(encoded)
	if err != nil {
		return nil, errors.New("knownprint: not a whsec_ secret")
	}
	mac := hmac.New(sha256.New, key)
	mac.Write([]byte(id + "." + stamp + "."))
	mac.Write(body)
	expected := mac.Sum(nil)
	matched := false
	for _, entry := range strings.Split(signatures, " ") {
		value, ok := strings.CutPrefix(entry, "v1,")
		if !ok {
			continue
		}
		candidate, err := base64.StdEncoding.DecodeString(value)
		if err != nil {
			continue
		}
		if hmac.Equal(candidate, expected) {
			matched = true
		}
	}
	if !matched {
		return nil, ErrVerification
	}
	var env Envelope
	if err := json.Unmarshal(body, &env); err != nil {
		return nil, ErrVerification
	}
	return &env, nil
}

func knownprintWebhook(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}
	// 1 MiB is a cap of your own choosing on what you read; knownprint sets no size for a delivery.
	body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	env, err := VerifyWebhook(r.Header, body, os.Getenv("KNOWNPRINT_WEBHOOK_SECRET"), time.Now())
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	log.Printf("knownprint delivery %s: %s", env.ID, env.Type)
	// Hand env to your own queue here, then answer.
	w.WriteHeader(http.StatusNoContent)
}

func main() {
	http.HandleFunc("/webhooks/knownprint", knownprintWebhook)
	log.Fatal(http.ListenAndServe(":3000", nil))
}
```

`strings.CutPrefix` needs Go 1.20 or later. Decode `env.Data` into a struct for each type you handle, for example:

```go
type AccountRelatedFound struct {
	VisitorID string `json:"visitor_id"`
	LinkedID  string `json:"linked_id"`
	Visitors  int    `json:"visitors"`
	LinkedIDs int    `json:"linked_ids"`
}
```

## Node SDK

:::note Coming
The Node SDK is coming with the SDK release. Until then, use the `node:crypto` code above, which checks the same things.
:::

The SDK's `Knownprint.verifyWebhook` is a static method: it needs only the secret, not a client.

```js
import { Knownprint, KnownprintWebhookError } from '@knownprint/sdk-node';

app.post('/webhooks/knownprint', express.raw({ type: 'application/json' }), (req, res) => {
  let envelope;
  try {
    envelope = Knownprint.verifyWebhook(
      req.headers,
      req.body,
      process.env.KNOWNPRINT_WEBHOOK_SECRET,
    );
  } catch (err) {
    if (err instanceof KnownprintWebhookError) return res.status(400).end();
    throw err;
  }
  queue.push(envelope);
  res.status(204).end();
});
```

`Knownprint.verifyWebhook(headers, rawBody, secret, options)`:

| Argument                   | Meaning                                                                                                |
| -------------------------- | ------------------------------------------------------------------------------------------------------ |
| `headers`                  | The request headers. Names are matched in any case; a repeated header's values are joined with a space |
| `rawBody`                  | The exact body received, as a `string` or `Uint8Array` (a `Buffer` is one)                             |
| `secret`                   | The `whsec_` secret. A value of another shape throws a `TypeError`                                     |
| `options.toleranceSeconds` | The allowed distance between `webhook-timestamp` and now, default `300`                                |
| `options.now`              | A function returning the current time in Unix milliseconds, default `Date.now`                         |

It returns the parsed envelope, or throws a `KnownprintWebhookError` whose `code` is the first check that failed:

| `code`                       | Meaning                                                                                                 |
| ---------------------------- | ------------------------------------------------------------------------------------------------------- |
| `missing_header`             | `webhook-id`, `webhook-timestamp` or `webhook-signature` is missing or empty                            |
| `timestamp_out_of_tolerance` | The timestamp is not a whole number of seconds within the tolerance of now                              |
| `bad_signature`              | No `v1` signature matches the body                                                                      |
| `invalid_body`               | The body is not UTF-8 JSON with exactly the envelope's members, `v` equal to `1` and a known event type |

[Node SDK](/sdks/node) covers the rest of the package.

## Rotate the secret

A webhook keeps the secret it was created with; no route changes or reads it. To replace a secret that may have leaked, or one you have lost:

1. Create a second webhook with the same URL and event types. Store its new secret.
2. Deploy your endpoint so that it accepts a delivery that verifies under either secret: try the new one, then the old one.
3. Delete the old webhook with [`DELETE /v1/webhooks/{id}`](/api/webhooks#delete-v1-webhooks-id). Its queued deliveries are deleted with it.
4. Remove the old secret from your endpoint.

While both webhooks exist, each change is delivered twice, once per webhook, with different delivery ids. Deduplicate on the content during that window, for example on `data.request_id` for `event.identified` (see [Ordering and duplicates](/webhooks#ordering-and-duplicates)).

## Troubleshooting

| Symptom                                                    | Likely cause                                                                                                                                                                        |
| ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Every delivery fails to verify                             | The body was parsed and re-serialised before verification, or the wrong secret is configured (a test environment's webhook and a live environment's webhook have different secrets) |
| Verification fails only behind a proxy or gateway          | Something in front of your application changes the body or drops the `webhook-*` headers                                                                                            |
| `timestamp outside the tolerance` on fresh deliveries      | Your server's clock is off by more than 5 minutes; enable NTP                                                                                                                       |
| The deliveries log shows `http_status` with `400` or `401` | Your endpoint rejected the delivery; check its logs for which check failed                                                                                                          |
| The deliveries log shows `http_status` with a `3xx`        | The URL redirects (for example `http` to `https`, or a missing trailing slash); register the final URL                                                                              |
| The deliveries log shows `timeout`                         | Your endpoint takes longer than 10 seconds to answer; answer first and do the work afterwards                                                                                       |
| The deliveries log shows `url_rejected` or `dns`           | The host name no longer resolves, or resolves to a private address                                                                                                                  |

After fixing the cause, [replay](/webhooks#replay-a-delivery) the deliveries that failed.
