Verifying HMAC-Signed Visitor Webhooks in Node.js

A forged or replayed webhook can poison your CRM, so verify in order.

· 9 min read · Updated
Cover illustration for “Verifying HMAC-Signed Visitor Webhooks in Node.js”
API and Webhook Recipes · October 17, 2026 · 9 min read · 1,972 words

Verifying HMAC-signed visitor webhooks in a server-side runtime requires more than matching a digest. The security guarantee depends on an ordered chain of raw body preservation, correct HMAC computation, timing-safe comparison, timestamp validation, and replay protection. Each check covers a different risk, and downstream CRM writes, Slack alerts, and audience updates can be trusted only when all the checks hold.

Why visitor webhook payloads demand a higher standard of verification than ordinary API calls

An unprotected webhook endpoint is a public URL that accepts any POST request. An attacker can submit a forged person.identified payload, fabricate a high-value prospect, and trigger workflows as though a real buyer had visited. Because visitor payloads carry enriched person-level data, accepting that request gives an invented identity a place in systems that treat it as evidence. The failure is not confined to the receiving route.

That consequence makes authentication a gate before ingestion and action. A forged event can add a CRM record, send a Slack message, or update a retargeting audience, and a replay can do those things again. Both failures corrupt the pipeline and its attribution. Before a delivery can affect downstream systems, the receiver must check that it is authentic, intact, fresh, and has not already been processed.

What HMAC-SHA256 actually does, and why each component of the verification chain exists

HMAC-SHA256 computes a digest from a message and a shared secret that never travels with the request. The receiver computes its own digest using the same secret and compares it with the sender’s signature. A match establishes that the message came from a holder of the expected secret and that its signed content was not changed. Stripe, GitHub, and Slack use HMAC-SHA256 for webhook authentication.

For the timestamp.rawBody convention, the signed message contains both the delivery timestamp and the original body bytes. Verification therefore begins by preserving those bytes, reconstructing the signed message, computing its hex-encoded HMAC, and comparing the result with a constant-time function. The format must match the provider’s contract exactly, even when a different format would carry the same JSON data. Signing the timestamp prevents it from being changed without invalidating the signature, but the receiver must still check its age. A replay cache then checks whether a delivery that passed the other checks has already been through the handler.

Capturing the raw request body in Express before any middleware touches it

The order in which Express middleware runs decides whether the receiver still has the message the sender signed. Mount express.raw({ type: "application/json" }) on the webhook route before any JSON parser middleware. This gives the handler a Buffer containing the original body byte stream. Keep that buffer intact and pass it directly into the verifier. Raw body capture is a prerequisite for verification.

In the broken setup, express.json() runs first, and the handler then tries to get the signed bytes back by serializing the object it made. Parsing and re-serialization can change whitespace, key ordering, or Unicode representation, leaving the handler with equivalent data but a different message. Computing an HMAC over that reconstruction checks bytes the sender did not sign. Converting the buffer to a string prematurely can also introduce encoding differences, so the verifier’s first argument should remain a raw Buffer. In Next.js route handlers, the equivalent starting point is await request.arrayBuffer() before any JSON parsing.

Reconstructing the signed payload and computing the HMAC correctly

Once the body is preserved, the verifier needs the signature, timestamp, and key ID, or kid, headers. Reject missing or malformed values before computing a digest, because requests with those values cannot pass verification. The kid selects the secret from the small set of active keys, including the current key and recently rotated keys still accepted. An unknown or expired key ID must fail without a search through other secrets. The timestamp must also pass the freshness guard before the cryptographic work begins.

For a provider that signs timestamp.rawBody, construct the input as Buffer.concat([Buffer.from(${timestampHeader}., "utf8"), rawBody]). The prefix preserves the timestamp header text and includes the dot delimiter, while the second buffer contributes the untouched body. Compute the expected signature with crypto.createHmac("sha256", secret).update(signedPayload).digest("hex"). This produces the hex-encoded digest for comparison with the received signature. A different delimiter, an omitted timestamp, or a reconstructed body can all produce a plausible digest that authenticates the wrong input, so this convention must never substitute for the provider’s documented format.

Using crypto.timingSafeEqual to prevent timing attacks on the comparison

Ordinary equality checks such as === do not provide a constant-time guarantee, and a comparison that stops at the first mismatch creates a timing-attack surface. Repeated probes can expose information about matching portions of the signature. Use crypto.timingSafeEqual() instead, so the comparison does not depend on where the mismatch occurs.

Validate the received hex representation before decoding it, then convert the received and expected values with Buffer.from(receivedHex, "hex") and Buffer.from(expectedHex, "hex"). A SHA-256 digest produces a 32-byte buffer. Reject unequal lengths before calling crypto.timingSafeEqual(), because the function throws when its inputs have different lengths. Timing-safe comparison is part of the HMAC verification guarantee.

Validating the timestamp to enforce a freshness window

Authenticity does not establish freshness. An attacker who captures a legitimate signed delivery can submit it again without changing its body or signature. Unless the receiver checks the timestamp, the HMAC can remain valid long after the original delivery.

Reject a timestamp that is non-numeric or non-finite before calculating its age. For a 300-second tolerance, the rejection condition is Math.abs(Date.now() / 1000 - timestamp) > 300, which checks the distance from the receiver’s current time in either direction. In Stripe’s SDKs, the default tolerance is 300 seconds. Providers with non-standard retry models may document a different window, and the verifier should follow that contract.

Place this guard before HMAC computation to reject obviously stale requests without spending work on a digest. At that stage, the timestamp is not yet authenticated, so passing the age check cannot authorize the request. Only the later HMAC match binds that timestamp to the body and establishes that it was not altered. The two checks work together as a security requirement.

Blocking replays that arrive within the freshness window using an event ID cache

The 5-minute window still permits a captured request to arrive again while its timestamp remains acceptable. Its signature and age will both pass, so neither check can distinguish it from a delivery not yet handled. After those checks succeed, use the event ID or nonce to test whether the delivery has already been accepted. This cache check is the last replay gate before business logic, following authentication.

Use Redis or an equivalent TTL store with an atomic set-if-absent operation, expressed in the notes as setIfAbsent(webhook:event:${eventId}, 300). If the key already exists, reject the delivery as a replay. Set the cache TTL to match the replay window so entries expire on their own. Where the payload has no stable event ID, require a nonce header and store that value in the same cache.

Replay protection and idempotency cover different paths to duplication. Storing the event ID under a unique constraint before mutating state also guards against duplicate processing through other paths, including internal retries. Business logic therefore still needs idempotency after the webhook has passed verification.

Assembling the complete verification sequence in the correct order

Diagram: The Five-Gate Verification Chain. Visualizes: Show a left-to-right or top-to-bottom sequential flow of the five ordered checks that every incoming webhook must pass before business logic runs: (1) Raw body preserved — bytes match what was…

The complete Express handler starts with the raw buffer, then extracts and validates the signature, timestamp, and kid headers. It rejects stale timestamps before looking up the active signing secret. It then reconstructs the provider’s signed message, computes HMAC-SHA256, and compares the digest with crypto.timingSafeEqual(). Only an authenticated, timely request proceeds to the event ID or nonce cache.

When the event ID is inside JSON, reading that ID necessarily requires deserialization after signature and timestamp verification. That parsing does not authorize business actions. The handler still has to reject replays, validate the payload schema, and run the accepted work idempotently. When a nonce header supplies the replay key, the cache check can precede JSON parsing.

Once those gates pass, return a 200 response quickly and defer heavy processing asynchronously. Holding the connection while doing downstream work risks a provider retry before the first delivery finishes. Log failures using reason codes such as MISSING_SIGNATURE, STALE_TIMESTAMP, UNKNOWN_KEY, INVALID_SIGNATURE, and REPLAY_DETECTED, without recording the secret or computed digest.

Managing signing secrets across key rotation and multiple environments

Give each endpoint and each environment, including development, staging, and production, its own secret. Reusing a test secret in production allows a test leak to cross that boundary, while sharing across endpoints spreads the effect of a compromise. Store secrets in a secrets manager and keep them out of source code and environment variables committed to version control. Give each active secret a stable kid so the receiver can pick it directly.

During rotation, there must be a short overlap when the sender signs with both old and new secrets and the receiver accepts either. The Standard Webhooks spec supports this through a space-delimited list of signatures in one header. Stripe’s “roll secret” keeps the old secret alive for up to 24 hours during rotation. The verifier must read headers in the provider’s rotation format, which may put more than one bare digest in a header. Logging the kid that verified each delivery keeps traffic using the old key visible so the overlap can end safely once retries are done.

Testing the verifier against real payloads before deploying to production

Synthetic tests can show that digest calculations work while missing how the middleware and delivery work around them. Framework body parsing, wrong secrets, stale clocks, and retry paths that bypass verification are all failure points to test at the endpoint. Start by capturing a real delivery on a local or tunnel endpoint. Compare its raw headers and body byte-for-byte with the input used to verify it against the stored secret. This tests the actual boundary between the HTTP request and the verifier.

Next, give the captured delivery a fresh timestamp and re-sign it with the same secret to confirm acceptance. Submit it with its original, now stale timestamp to confirm rejection on age. Send the event that was already accepted again with a fresh, correctly signed timestamp to check that the replay cache rejects it. Mutate one body byte without updating the signature to confirm that the HMAC check rejects the changed content.

Provider retries must also go through the full sequence, with no path that skips verification. Confirm that an already accepted retry reaches the event ID cache and is rejected there. A passing synthetic test suite is necessary but not sufficient. At least one test against a real signed delivery is required before production.

How verified visitor webhooks connect to the broader pipeline they protect

A verified person.identified event is the trust anchor for the actions that consume it. Those actions include CRM writes to HubSpot, Salesforce, or Attio, Slack alerts carrying name, title, LinkedIn, and email, and ad-audience syncs to Google, Meta, and LinkedIn. Enrichment waterfalls may then add more to the record. Each consumer depends on the receiving boundary to tell an authentic event from a made-up signal.

That reliance matters because person-level identification can carry name, email, phone, LinkedIn, seniority, job function, ICP flag, CRM status, traffic source, and a full page-view and behavioral journey. The depth of a record does not establish its origin. Without verification, an apparently rich prospect can still be an invented buyer that wastes SDR time and pollutes audience data.

Platforms can expose visitor data through HMAC-signed webhooks, a REST API, bulk CSV export, and a remote MCP connector, allowing it to reach business tools and assistants such as Claude, ChatGPT, and Codex. In that broader pipeline, webhook verification guards the event-driven entry point. Preserved bytes establish what was signed, the HMAC authenticates it, and freshness and replay checks constrain when it may be accepted.

More in API and Webhook Recipes