A webhook endpoint is an open HTTP route on your server. Anyone on the internet who knows or guesses the URL can send an HTTP POST request to it. If your endpoint accepts events like payment.succeeded, subscription.deleted, or pull_request.opened without verification, an attacker could fake invoices, credit balances, or trigger unintended background jobs.
To guarantee that a webhook was actually dispatched by the service you trust and that the payload was not modified in transit, providers sign every outgoing payload using an HMAC (Hash-based Message Authentication Code) with a shared secret.
This guide explains how HMAC signatures work across major platforms, how to verify them securely, and how to avoid the three common implementation bugs that leave apps vulnerable.
How HMAC signature verification works
When you configure a webhook in Stripe, GitHub, Slack, or Shopify, you receive a Signing Secret (often prefixed with whsec_ or stored as an environment variable).
- At the provider: When an event occurs, the provider takes the raw HTTP request body (and usually a timestamp), creates a cryptographic hash using your shared secret via
HMAC-SHA256, and sends the signature in an HTTP request header. - At your server: Your endpoint receives the raw request body and the signature header. You independently compute the HMAC-SHA256 signature using your copy of the secret.
- The comparison: If your computed signature matches the header signature exactly, the payload is authentic and untampered. If they differ, you reject the request with HTTP 400 or 401.
Because only you and the provider know the secret, a third party cannot forge a valid signature for an altered payload.
Provider signature formats
Different providers format and transmit their signatures differently:
| Provider | Signature Header | What is Signed | Format |
|---|---|---|---|
| GitHub | X-Hub-Signature-256 | Raw request body | sha256=<hex_digest> |
| Stripe | Stripe-Signature | <timestamp>.<raw_body> | t=<timestamp>,v1=<hex_digest> |
| Slack | X-Slack-Signature | v0:<timestamp>:<raw_body> | v0=<hex_digest> |
| Shopify | X-Shopify-Hmac-Sha256 | Raw request body | <base64_digest> |
Stripe and Slack include the Unix timestamp in the signature calculation to prevent replay attacks (explained below).
Three critical pitfalls to avoid
1. The parsed body trap (The #1 bug)
This is by far the most frequent reason signature verification fails. Most web frameworks (Express, Next.js, Fastify, Flask) automatically parse incoming JSON payloads into language objects (req.body = JSON.parse(rawText)).
If you attempt to re-stringify the object to calculate the HMAC:
// ❌ WRONG: Re-stringifying changes whitespace and key order!
const bodyString = JSON.stringify(req.body);
const hash = crypto.createHmac('sha256', secret).update(bodyString).digest('hex');JSON stringification does not preserve original key order, indentation, or Unicode escapes. A single space discrepancy produces a completely different SHA-256 digest. You must capture the raw byte buffer before JSON parsing occurs.
In Node.js / Express:
import express from 'express';
const app = express();
// Use express.raw() or capture the raw buffer in verify option
app.use('/api/webhooks', express.raw({ type: 'application/json' }));In Next.js App Router (route.ts):
export async function POST(req: Request) {
// Read the raw body as text or arrayBuffer directly from the request
const rawBody = await req.text();
// Verify before JSON.parse()
const payload = JSON.parse(rawBody);
}2. Timing attack vulnerabilities
When comparing your calculated signature with the header signature, never use standard equality operators like == or ===.
// ❌ VULNERABLE TO TIMING ATTACKS
if (computedSignature === headerSignature) { ... }Standard string comparisons return false as soon as the first non-matching byte is found. An attacker can measure differences in nanoseconds to guess characters of the signature one by one.
Always use a constant-time comparison function like Node.js's crypto.timingSafeEqual:
import crypto from 'node:crypto';
function secureCompare(a: string, b: string): boolean {
const bufA = Buffer.from(a, 'utf8');
const bufB = Buffer.from(b, 'utf8');
if (bufA.length !== bufB.length) {
return false;
}
return crypto.timingSafeEqual(bufA, bufB);
}3. Ignoring replay attacks
If an attacker intercepts a legitimate webhook request over an insecure link or proxy, they could re-send the exact same signed request multiple times (for example, re-triggering a refund or order fulfillment).
To stop replay attacks:
- Extract the timestamp from the signature header (e.g.,
t=1760000000in Stripe orX-Slack-Request-Timestamp). - Reject requests whose timestamp is older than a tolerance threshold (typically 5 minutes):
const tolerance = 5 * 60; // 5 minutes in seconds
const currentTime = Math.floor(Date.now() / 1000);
if (Math.abs(currentTime - eventTimestamp) > tolerance) {
throw new Error('Webhook timestamp too old or outside tolerance window');
}Complete Node.js / TypeScript verification example
Here is a production-grade verification function supporting Stripe-style timestamped webhooks:
import crypto from 'node:crypto';
interface VerifyOptions {
rawBody: string;
signatureHeader: string;
secret: string;
toleranceSeconds?: number;
}
export function verifyStripeWebhook({
rawBody,
signatureHeader,
secret,
toleranceSeconds = 300,
}: VerifyOptions): boolean {
// 1. Parse header components (e.g. t=1760000000,v1=abcdef...)
const parts = signatureHeader.split(',');
const timestampPart = parts.find((p) => p.startsWith('t='));
const signaturePart = parts.find((p) => p.startsWith('v1='));
if (!timestampPart || !signaturePart) {
return false;
}
const timestamp = parseInt(timestampPart.slice(2), 10);
const signature = signaturePart.slice(3);
// 2. Prevent replay attacks
const now = Math.floor(Date.now() / 1000);
if (Math.abs(now - timestamp) > toleranceSeconds) {
return false;
}
// 3. Compute expected signature
const payloadToSign = `${timestamp}.${rawBody}`;
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(payloadToSign, 'utf8')
.digest('hex');
// 4. Constant-time comparison
const expectedBuf = Buffer.from(expectedSignature, 'utf8');
const actualBuf = Buffer.from(signature, 'utf8');
if (expectedBuf.length !== actualBuf.length) {
return false;
}
return crypto.timingSafeEqual(expectedBuf, actualBuf);
}Testing your webhook integration
When debugging webhook issues locally, testing HMAC calculations manually saves hours of frustration.
- Use the Webhook Signature Verifier to paste your raw payload, secret, and signature header to immediately check if your HMAC and formatting match.
- If you need an active endpoint to catch incoming requests from Stripe or GitHub and see their raw body and headers live, use the Webhook Tester.
- For testing custom HMAC algorithms (SHA-1, SHA-384, SHA-512) or checking password hashes, visit the HMAC & Bcrypt Generator.