Verify webhook signatures and handle duplicate deliveries

Authenticate the raw request body on your receiver and use the event ID to make retries safe.

Keep the request body as raw bytes until verification is complete. Bettercom signs the Unix timestamp, a period, and the original JSON bytes. Reformatting parsed JSON changes the signature input.

import { createHmac, timingSafeEqual } from 'node:crypto';

function validSignature(rawBody, timestamp, signature, secret) {
  if (!/^v1=[0-9a-f]{64}$/.test(signature ?? '')) return false;
  const expected = createHmac('sha256', secret)
    .update(timestamp + '.')
    .update(rawBody)
    .digest();
  return timingSafeEqual(expected, Buffer.from(signature.slice(3), 'hex'));
}

Read the timestamp from X-Bettercom-Timestamp and the signature from X-Bettercom-Signature. After verification, parse the body and use its signed id as the durable deduplication key. It matches X-Bettercom-Event. Apply the downstream change once per event ID and return success for a verified duplicate.

If validation fails, compare the receiver’s secret with the one created for this subscription and verify that the framework exposes the original body bytes.

Related reading

Was this article helpful?