Webhook Hmac Validation: How to Verify Signatures Using the Raw Request Body
To validate a webhook HMAC signature, compute the provider-specified HMAC over the exact request-body bytes you received, decode the supplied signature according to the provider’s format, and compare the two byte sequences with a timing-safe comparison. Do this before parsing the JSON or acting on the event. Parsing and re-serializing the body can change its bytes, causing a valid signature to fail.

The procedure is straightforward, but the provider’s signing specification controls the details. Confirm the algorithm, which bytes are signed, the signature header’s encoding, and whether a timestamp or other fields are part of the signed message. The example below shows a raw-body HMAC-SHA-256 pattern; it is not a drop-in verifier for every webhook provider.
What the raw request body means
The raw body is the byte sequence delivered to your application as the HTTP request payload, before a JSON parser turns it into an object. HMAC operates on bytes, not on the meaning of a JSON document. These bodies can represent the same JSON value while producing different HMACs:
{"status":"delivered","id":42}
{"id":42,"status":"delivered"}Whitespace, key order, line endings, and character encoding can also affect the byte sequence. Even an apparently harmless operation such as calling JSON.stringify on a parsed object can produce a different message. For a scheme that signs the body itself, pass the captured raw bytes to the HMAC function. Parse the JSON only after the signature check succeeds.
“Raw” here refers to the bytes available at the application boundary where verification runs. If an intermediary rewrites the payload before it reaches that boundary, your application cannot reconstruct the original signed bytes. Design the delivery path so intermediaries do not transform signed content, and investigate any proxy or middleware that may do so.
Confirm the signing contract before writing code
A receiver cannot safely infer a signature scheme from a header name. Obtain the provider’s webhook documentation and identify:
- The signed message: Is it the body alone, or a defined combination of a timestamp, delimiter, and body? If a timestamp is included, use the exact documented construction.
- The algorithm and key: Confirm the HMAC algorithm and which webhook secret applies to this endpoint. An API token or a public identifier is not automatically the signing key.
- The header format: The value may be hexadecimal, Base64, or a structured string containing a version or multiple signatures. Decode it according to its specification.
- Rotation and replay rules: Check whether multiple active secrets can be valid and whether the provider signs a timestamp that should be checked for freshness.
- Transport details: Confirm which requests reach the endpoint, including the documented content type and any size limits you need to accommodate.
The general workflow is capture bytes → build the documented signed message → calculate HMAC → compare securely → process the event. The “build” step matters: a correct HMAC over the wrong message is still a failed verification.
Implement raw-body verification in Express
The following Node.js example assumes an illustrative provider signs only the body bytes with HMAC-SHA-256 and places a 64-character hexadecimal digest in a single X-Webhook-Signature header. Those assumptions are part of this example, not a claim about any particular service. Replace them with your provider’s documented contract.
const express = require('express');
const crypto = require('node:crypto');
const app = express();
const secret = process.env.WEBHOOK_SIGNING_SECRET;
if (!secret) {
throw new Error('WEBHOOK_SIGNING_SECRET is required');
}
// Register this route before any app-wide JSON body parser.
app.post(
'/webhooks',
express.raw({ type: 'application/json', limit: '1mb' }),
(req, res) => {
const signature = req.get('x-webhook-signature');
if (!Buffer.isBuffer(req.body) ||
typeof signature !== 'string' ||
!/^[0-9a-fA-F]{64}$/.test(signature)) {
return res.sendStatus(400);
}
const expected = crypto
.createHmac('sha256', secret)
.update(req.body)
.digest();
const received = Buffer.from(signature, 'hex');
if (!crypto.timingSafeEqual(expected, received)) {
return res.sendStatus(401);
}
let event;
try {
event = JSON.parse(req.body.toString('utf8'));
} catch {
return res.sendStatus(400);
}
// Persist or enqueue the verified event before acknowledging it.
// Apply your application's event validation and deduplication rules.
return res.sendStatus(204);
}
);
// Add an app-wide express.json() parser here, if other routes need it.
app.use(express.json());express.raw() supplies a Buffer for matching requests. The example’s type and limit are configuration choices, not universal webhook requirements. Adjust them to the content types and legitimate payload sizes specified for your integration. If a request does not match the raw parser’s configured media type, do not silently treat an absent body as a valid empty payload.
Route order is deliberate. If an earlier middleware has already parsed or consumed the request stream, adding a raw parser inside the handler will not recover the original bytes. Configure raw-body capture at the point where the request first enters your parsing pipeline. Frameworks with automatic request parsing need an equivalent route-level exception or a documented raw-body facility.
The code checks that the signature is valid hexadecimal of the expected length before decoding it. Node.js’s timingSafeEqual requires inputs of equal byte length; validating the format first both prevents a length error and avoids accepting a truncated or ambiguously decoded value. Some providers supply several candidate signatures during secret rotation. In that case, parse the header as documented and check each allowed candidate against the appropriate active secret; do not invent a format by splitting an unfamiliar header.
Validate first, then decide how to process the event
A valid HMAC establishes that the message matches the signing scheme and a secret known to the sender and receiver. It does not prove that the JSON has the fields your application expects, that the event has not been delivered before, or that processing it is safe. After verification, validate the event schema and relevant identifiers before changing records or triggering downstream work.
Keep the webhook secret in your application’s secret-management or environment configuration rather than in source code. Use the secret designated for the specific endpoint or environment. If secrets rotate, maintain the documented overlap between old and new keys; remove retired keys when the rotation is complete. Treat a leaked secret as a compromised authentication credential and follow the provider’s rotation procedure.
Webhook deliveries may be retried, so make side effects idempotent where possible. If the provider supplies a stable event identifier, record it and avoid applying the same event twice. A signed timestamp, where the provider supports one, can help limit replay within a documented tolerance. A timestamp that is not included in the authenticated message cannot, by itself, provide that protection. These checks complement HMAC validation rather than replacing it.
Return an acknowledgment only after the work you promise to retain has been safely accepted, such as committing an event record or enqueueing a job. A valid signature alone does not mean the business operation succeeded. Follow the provider’s delivery and retry documentation when choosing response codes and deciding whether to process synchronously.
Diagnose signature mismatches systematically
When verification fails, resist the temptation to remove the check “just to test the webhook.” Start with the parts of the signed-message contract most likely to be wrong:
- Check the secret. Confirm you are using the webhook signing secret for the correct endpoint and environment, not a general API credential.
- Check the exact message. Determine whether the provider signs the body alone or a timestamp-prefixed message. Preserve the documented delimiter and encoding.
- Check the captured bytes. Verify that your handler receives a
Bufferor equivalent raw byte sequence before parsing. Look for earlier middleware and payload-transforming intermediaries. - Check the signature representation. Do not compare a hexadecimal string with a Base64 string or decode a structured header as though it were a bare digest.
- Check algorithm and rotation settings. Use the specified HMAC algorithm and allow only secrets that are currently authorized for verification.
- Check the test request. If a local test signs one string but sends a separately serialized JSON object, the receiver may get different bytes.
For debugging, you can log a request identifier, verification outcome, content type, and body length. Avoid logging signing secrets or full sensitive payloads. If your security policy permits diagnostic digests, treat them as operational data and remove temporary logging after resolving the issue.
Test with byte-level fixtures
A useful test harness starts with a fixed Buffer, computes its HMAC using a test secret, and sends those same bytes with the matching header. Then change one byte without updating the header and confirm the request is rejected. This distinguishes working verification from a handler that merely checks whether a header exists.
Include a valid body with different whitespace or property order and sign that exact new body. It should verify, because the signature corresponds to the bytes actually sent. By contrast, sending those changed bytes with the original signature should fail. Test malformed hexadecimal, a missing header, an unexpected content type, an oversized body, invalid JSON with a valid signature, and duplicate delivery. Each case exercises a different boundary: authentication, parser configuration, application validation, or idempotency.
When the provider offers a documented test delivery or signature fixture, use it as an additional integration check. A locally generated HMAC proves that your own sender and receiver agree; it does not, on its own, prove that you implemented the provider’s precise header and signed-message format.
FAQ
Can I verify a webhook after parsing its JSON?
You can parse the event after verification, but do not calculate a raw-body signature from the parsed object. Re-serializing an object can change whitespace, key order, or other bytes. Capture the original body first, verify it, and then parse it.
Should I compare signature strings with a normal equality operator?
Use a timing-safe comparison for the decoded digest bytes. Validate the signature’s format and expected length before comparing, because timing-safe comparison functions commonly require equal-length inputs. A timing-safe function is only one part of a secure verifier; the signed message and secret must also be correct.
Is HMAC validation the same as encrypting the webhook?
No. HMAC provides a way to check message authenticity and integrity under a shared secret. It does not hide the payload. Use HTTPS for transport protection, and apply appropriate access controls to stored webhook data.
What if the provider signs a timestamp as well as the body?
Follow its documented message construction exactly. Typically, that means retrieving the timestamp from the specified header, checking its permitted age, and computing the HMAC over the prescribed combination of timestamp and raw-body bytes. Do not substitute a generic timestamp format or authenticate the body alone.
Why does the signature fail only in production?
Compare production and test environments for different secrets, parser order, content-type handling, proxy behavior, and signing configurations. Confirm that the bytes passed to HMAC in production are the bytes delivered to the verifier, not a reconstructed JSON string.
Sources
- GitHub Docs: Validating webhook deliveries — an example of provider-specific webhook signature validation.
- Stripe Docs: Resolve webhook signature verification errors — guidance on preserving the raw request body for signature verification.
- Express API: express.raw() — raw-body middleware behavior and configuration.
- Node.js Crypto API: crypto.createHmac() — HMAC generation.
- Node.js Crypto API: crypto.timingSafeEqual() — timing-safe byte comparison and its equal-length requirement.


