API Engineering

Webhook Signature Verification: Implementing HMAC SHA-256 in Node.js and Python

Secure your webhook endpoints against forgery with cryptographic HMAC SHA-256 signatures. Complete verification code using timing-safe comparisons.

By Cometflow API Engineering Team • Updated 2026-10-06

Because webhook receivers are publicly reachable URLs, you must never trust an incoming POST body based solely on IP address or user-agent. Providers sign the raw request body using a shared secret with HMAC-SHA256 so your server can verify authenticity.

1. Timing-Safe HMAC Verification in Node.js

import crypto from 'node:crypto';

export function verifyWebhookSignature(
  rawBody: Buffer,
  signatureHeader: string,
  secret: string
): boolean {
  const expected = crypto
    .createHmac('sha256', secret)
    .update(rawBody)
    .digest('hex');

  const sigBuffer = Buffer.from(signatureHeader, 'utf8');
  const expectedBuffer = Buffer.from(expected, 'utf8');
  if (sigBuffer.length !== expectedBuffer.length) return false;

  return crypto.timingSafeEqual(sigBuffer, expectedBuffer);
}

Frequently Asked Questions (FAQ)

Why does HMAC verification fail if I pass JSON.stringify(req.body)?

Re-serializing a parsed JavaScript object changes whitespace and key ordering, producing a completely different SHA-256 digest. Always compute the HMAC over the exact unparsed raw request bytes.