An HMAC signature only proves anything if you hash the exact bytes the sender signed. While testing the old Code-node snippet from an earlier version of this guide (which hashed JSON.stringify($json.body)) it rejected a validly signed request whose JSON payload had spaces after the colons and commas ({"event": "order.paid", "id": 1042}). Switching the Webhook node to Raw Body and hashing the raw binary buffer inside the Code node passed both compact and spaced payloads, and pairing it with a Respond to Webhook node let n8n return a real HTTP 401 instead of a generic HTTP 500 workflow error.
What you need in place before testing:
- Raw bytes, not re-serialized JSON: Turn on Options → Raw Body on the Webhook node and read
await this.helpers.getBinaryDataBuffer(0, 'data')in the Code node so formatting differences never change the digest. - Two container environment flags: Set
NODE_FUNCTION_ALLOW_BUILTIN=cryptoandN8N_BLOCK_ENV_ACCESS_IN_NODE=falseindocker-compose.yml(alongsideWEBHOOK_SHARED_SECRET) so the Code node can load Node'scryptomodule and read$env. - Explicit HTTP status control: Set the Webhook node's Respond parameter to Using 'Respond to Webhook' Node so rejected signatures get
HTTP 401(or409on replay) instead ofHTTP 200orHTTP 500.
Tested on: Windows 11 Pro 23H2 | WSL 2 Linux Kernel 6.6.87.2-microsoft-standard-WSL2 | Official Docker Engine 27.3.1, build ce12230 (desktop-linux) + Docker Compose v2.29.7 | n8nio/n8n:1.76.1 (127.0.0.1:5679:5678) + postgres:16-alpine + node:20-alpine | Empirical Lab Baseline: 2025-01-29 ~ 2025-01-30.
What I Ran
I ran n8nio/n8n:1.76.1 in Docker Desktop on Windows 11 (Docker Engine 27.3.1, Compose v2.29.7) and built two active workflows side by side (when promoting verified webhook receivers from a sleeping laptop to a 24/7 Linux server without breaking encrypted credentials, see our Docker n8n WSL2-to-Droplet migration guide):
- Workflow A (the old code from this guide):
Webhook(POST, Respond =When Last Node Finishes, Raw Body off) →Codenode that hashesJSON.stringify($json.body)and throwsnew Error('401 Unauthorized: ...')on failure → no-opBusiness step. - Workflow B (raw-body version):
Webhook(POST, Options → Raw Body on, Respond =Using 'Respond to Webhook' Node) →Codenode that hashes the raw request bytes →Respond to Webhooknode returning200or401:


item.json strips whitespace and breaks valid signatures on spaced payloads, whereas enabling Webhook Raw Body with Node's crypto.timingSafeEqual and a Respond to Webhook 401 branch verifies exact wire bytes safely.From the Windows host I signed five test requests in Python with hmac.new(secret, raw_bytes, hashlib.sha256).hexdigest(), attached the digest as X-Hub-Signature-256: sha256=<hex>, and sent the exact byte buffer with curl --data-binary so curl would not strip newlines or alter whitespace:
- Valid signature over compact JSON:
{"event":"order.paid","id":1042}(32 bytes). - Valid signature over the same JSON with spaces after the colons and comma:
{"event": "order.paid", "id": 1042}(35 bytes). - Signature computed with a second, unrelated secret over the 32-byte payload.
- Body changed by 1 byte after signing (
1042→1043) while keeping the Case 1 signature header. X-Hub-Signature-256header omitted completely.
Results: Old Code vs Raw-Body Version
Test Case Sent with curl --data-binary |
Old Code (JSON.stringify($json.body)) |
Raw Body + Respond to Webhook Node |
|---|---|---|
| 1. Correct signature, compact JSON (32 bytes) | HTTP 200 (passed) |
HTTP 200 {"valid":true,"reason":"ok"} |
| 2. Correct signature, JSON with spaces (35 bytes) | HTTP 500: 401 Unauthorized: Signature hash verification failed |
HTTP 200 {"valid":true,"reason":"ok"} |
| 3. Signature made with another secret | HTTP 500: 401 Unauthorized: Signature hash verification failed |
HTTP 401 {"valid":false,"reason":"signature mismatch"} |
4. Body changed by 1 byte (1042 → 1043) |
HTTP 500: 401 Unauthorized: Signature hash verification failed |
HTTP 401 {"valid":false,"reason":"signature mismatch"} |
| 5. Signature header missing | HTTP 500: 401 Unauthorized: Missing webhook signature |
HTTP 401 {"valid":false,"reason":"missing signature header"} |

Three specific behaviors stood out from the five test cases in Run 2:
- The old code rejected a valid request (Case 2): The sender signed the 35-byte string
{"event": "order.paid", "id": 1042}. Before the Code node ran, n8n parsed that JSON into an object on$json.body. When the Code node calledJSON.stringify($json.body), V8 serialized the object without spaces as{"event":"order.paid","id":1042}(32 bytes). Hashing those 32 bytes produced a completely different SHA-256 digest, so a genuinely signed webhook failed verification. - The "401" in the old code was only error text inside n8n: Writing
throw new Error('401 Unauthorized: ...')inside a Code node causes the workflow execution to fail. With the Webhook node set toWhen Last Node Finishes, n8n responds to the caller withHTTP 500and the body{"message":"Error in workflow"}, never anHTTP 401status code. - Header names arrive in lower case: Even though curl sent
X-Hub-Signature-256, n8n stored it under$json.headers['x-hub-signature-256']. Reading the mixed-case key returnsundefined.
![n8n execution view ID#22 at 23:53:48 showing Problem in node Verify HMAC (post code): 401 Unauthorized: Signature hash verification failed [line 29] when testing Case 2 validly signed 35-byte JSON with spaces](https://i0.wp.com/gearflowlab.com/wp-content/uploads/2026/11/IMG_03_B_rescued_orig4270_code_node_signature_verification_failed_retina-1.webp?resize=1920%2C1020&ssl=1)
In Execution ID#22 (23:53:48, completed in 21ms) shown above, the green check mark on the Webhook node confirms that n8n accepted the HTTP POST request and emitted 1 item into the workflow. However, because Raw Body was turned off on that Webhook node, n8n's Express body parser decoded the incoming application/json stream into a JavaScript object before handing the item to Verify HMAC (post code).
Any formatting choice made by the sender, spaces after colons, pretty-printed indentation, trailing newlines, floating-point representation such as 10.0 versus 10, or non-default key ordering, is erased the moment the payload is parsed into a JavaScript object. In addition, throwing an uncaught Error at line 29 leaves the downstream Business step unexecuted, which protects your database, but returning HTTP 500 tells webhook providers like Stripe, GitHub, and Shopify that your server crashed, triggering hours of unnecessary automatic retries:

The Two Errors Before Any Signature Was Checked
Before Run 2 ever reached the HMAC comparison in either workflow, every single curl request in my first two container runs failed immediately with HTTP 500 {"message":"Error in workflow"}. Inspecting the failed executions inside n8n showed two separate sandbox restrictions in n8nio/n8n:1.76.1:
- Run 0 (default container environment): Every request failed at line 1 of the Code node with
Module 'crypto' is disallowed [line 1]. By default, n8n's Code node sandbox blocks built-in Node.js modules unless you explicitly allow them viaNODE_FUNCTION_ALLOW_BUILTIN=crypto. - Run 1 (added
WEBHOOK_SHARED_SECRETandNODE_FUNCTION_ALLOW_BUILTIN=crypto): Every request then failed at the$env.WEBHOOK_SHARED_SECRETlookup withaccess to env vars denied. Inn8n 1.76.1, reading$envinside a Code node is blocked unless you also setN8N_BLOCK_ENV_ACCESS_IN_NODE=false(or store the secret inside n8n Credentials instead of an environment variable).
![Split terminal comparison showing Run 0 failing with Module crypto is disallowed [line 1] and Run 1 failing with access to env vars denied versus Run 2 succeeding with NODE_FUNCTION_ALLOW_BUILTIN=crypto and N8N_BLOCK_ENV_ACCESS_IN_NODE=false](https://i0.wp.com/gearflowlab.com/wp-content/uploads/2026/11/IMG_05_D_run0_crypto_disallowed_vs_run1_env_denied_vs_run2_allowed_split-1.webp?resize=1920%2C1020&ssl=1)
Adding N8N_BLOCK_ENV_ACCESS_IN_NODE=false in Run 2 allowed both workflows to load crypto, read $env.WEBHOOK_SHARED_SECRET, and reach the signature check. (At container startup, n8n also printed a deprecation warning for N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS, so I included N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS=true in the Compose file as well.)
Respond = Immediately: The Sender Always Sees 200
Because n8n's Webhook node defaults to Respond: Immediately when you first drop it onto the canvas, I also tested placing the old Code node behind a Webhook node left on Respond: Immediately.
Right after activating that workflow from the CLI, the first batch of curl requests got HTTP 404 with {"code":404,"message":"The requested webhook \"POST gfl-hmac-post-immediate\" is not registered."}. Re-sending the exact same requests 14 seconds later (at 23:54:24) without touching the container returned:
- Case 1 (correct signature):
HTTP 200,{"message":"Workflow was started"}. - Case 3 (signature made with another secret):
HTTP 200,{"message":"Workflow was started"}. - Case 5 (signature header missing):
HTTP 200,{"message":"Workflow was started"}.
Inside n8n, Cases 3 and 5 still failed in the Code node and stopped before the business step, so the bad data was not processed, but the HTTP client had already received 200 OK before the Code node ever ran:

The Setup That Worked
Step 1: Docker Compose Environment
Start n8nio/n8n:1.76.1 with the shared webhook secret and the two sandbox flags required by the Code node:
services:
n8n:
image: n8nio/n8n:1.76.1
restart: unless-stopped
ports:
- "127.0.0.1:5679:5678"
environment:
- GENERIC_TIMEZONE=Asia/Seoul
- WEBHOOK_SHARED_SECRET=replace-with-your-secret
- N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS=true
- NODE_FUNCTION_ALLOW_BUILTIN=crypto
- N8N_BLOCK_ENV_ACCESS_IN_NODE=false
volumes:
- n8n_data:/home/node/.n8n
volumes:
n8n_data:
Apply the configuration with docker compose up -d so the recreated container picks up the environment variables.
Step 2: Webhook Node
- HTTP Method:
POST - Respond:
Using 'Respond to Webhook' Node - Options → Raw Body:
On(stores the raw request bytes in the binary propertydata; in my test runs the 32-byte and 35-byte JSON payloads appeared there withmimeType: text/plain).
Step 3: Code Node That Hashes the Raw Bytes
Add a Code node after the Webhook node (Mode: Run Once for All Items, Language: JavaScript) that reads the binary buffer via this.helpers.getBinaryDataBuffer(0, 'data').
Keep the a.length === b.length check before calling crypto.timingSafeEqual(a, b). In a separate Node.js test outside n8n (/lab/hmac_reserialize.js), passing a sha256=<hex> buffer (71 bytes) and a bare <hex> buffer (64 bytes) to crypto.timingSafeEqual threw ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH: Input buffers must have the same byte length instead of returning false:

That standalone Node.js check confirmed all three cryptographic rules in isolation: hashing the 35-byte raw buffer ({"event": "order.paid", "id": 1042}) verified true, hashing the 32-byte output of JSON.stringify(JSON.parse(raw)) verified false under the exact same secret, and calling crypto.timingSafeEqual on unequal buffer lengths threw a runtime RangeError.
Step 4: Respond to Webhook Node (200 or 401)
Connect a Respond to Webhook node after the Code node so the caller receives an accurate HTTP status code without crashing the workflow execution:
- Respond With:
JSON - Response Body:
={{ JSON.stringify({ valid: $json.valid, reason: $json.reason }) }} - Options → Response Code:
={{ $json.valid ? 200 : 401 }}
With those three nodes wired together in Workflow B, n8n buffers the raw request stream, verifies the SHA-256 HMAC in constant time, and replies with 200 or 401:

In my initial 5-case test, the Respond to Webhook node was the last node in Workflow B, so rejected requests got an HTTP 401 response and nothing else ran. When you attach real business logic (such as database writes, Slack alerts, or CRM updates) after the signature check, place an If node checking {{ $json.valid === true }} between the Code node and your downstream steps, routing the true branch to your business logic (and a 200 Respond node) and the false branch directly to a 401 Respond node.
Without that If branch, n8n will send the HTTP 401 response back to the webhook sender and then continue executing whatever nodes are connected after the Respond to Webhook node. The complete side-by-side docker-compose.yml and verify_hmac_raw_bytes.js implementation is shown below:

With both environment variables active inside docker-compose.yml and the Code node reading await this.helpers.getBinaryDataBuffer(0, 'data'), re-running all five curl --data-binary requests against Workflow B (/webhook/gfl-hmac-raw-body) produced the exact HTTP responses expected by a webhook sender: both the 32-byte compact JSON payload (Case 1) and the 35-byte spaced JSON payload (Case 2) returned HTTP/1.1 200 OK with {"valid":true,"reason":"ok"}, while the wrong-secret request (Case 3), the 1-byte edited body (Case 4), and the missing-header request (Case 5) returned HTTP/1.1 401 Unauthorized.
Other Senders and Other Protections
Before adapting this three-node pattern to third-party SaaS webhooks or high-value payment events, compare how your specific sender formats its signature header and what an HMAC over the body alone does not cover:

- The code above expects GitHub's header format: GitHub sends
X-Hub-Signature-256: sha256=<hex>computed directly over the raw request body. Other providers sign different strings or use different encodings: for example, Stripe sendsStripe-Signature: t=<unix-seconds>,v1=<hex>where the HMAC is computed over<timestamp>.<raw_body>, while Shopify sends a Base64-encoded SHA-256 digest inX-Shopify-Hmac-SHA256without a prefix (requiring.digest('base64')or comparing 32-byte raw buffers viaBuffer.from(sig, 'base64')). Always match the header name, prefix, signed string construction, and buffer encoding to your sender's specification. - A body-only signature check does not stop a replay attack: If an attacker or misconfigured proxy captures a validly signed request on the wire and sends the exact same bytes and header a second time, a timeless HMAC check over the body will pass again.
- n8n's built-in Webhook authentication checks static credentials, not a body HMAC: The Webhook node's built-in Basic, Header, and JWT authentication options verify credentials in the headers, not an HMAC digest over the request payload.

Adding a 300-Second Timestamp Window and Replay Check
To prevent a captured valid request from being replayed, the sender must include a timestamp inside the signed payload and the receiver must reject both stale timestamps and previously seen signatures. I ran a second empirical test (W1, workflow name gfl 2082 v2: timestamp + replay) on 2025-01-30 with Postgres alongside n8n and a Stripe-style header:
- Header format:
X-GFL-Signature: t=<unix_seconds>,v1=<hex>, wherev1isHMAC-SHA256(secret, t + "." + raw_body). - Code node: Reads the raw binary buffer, checks that the header uses
,(not;) and includes bothtandv1, checks thatMath.abs(now - t) <= 300(a 300-second tolerance window), and verifiesv1withcrypto.timingSafeEqual. - Replay table in Postgres: For requests that pass the Code node, a Postgres node runs an atomic
INSERT ... ON CONFLICT (signature) DO NOTHINGquery that returnsclaimed = 1on first delivery andclaimed = 0on a duplicate delivery. - Responses and error reporting: Valid first deliveries return
HTTP 200; malformed headers returnHTTP 400; bad signatures or out-of-window timestamps returnHTTP 401; replayed signatures returnHTTP 409 Conflict; and rejected branches hit a Stop And Error node connected to an Error Trigger workflow.
All 15 curl test cases returned the expected HTTP status code (PASS 15 / 15):

Testing the Error Trigger workflow across two runs exposed an important operational detail in n8nio/n8n:1.76.1. For rejected requests, the main workflow (W1, ID uNdJvS24S5GbleHv) first sends the 400, 401, or 409 response via Respond to Webhook and then executes a Stop And Error node so that n8n invokes the configured error workflow (ID yRGRaa9pgwUhDuOp, containing Error Trigger → HTTP Request to a local receiver).
In Run 1, my local error receiver got zero reports. Inspecting the n8n container logs revealed why:
Calling Error Workflow for "uNdJvS24S5GbleHv". Workflow "yRGRaa9pgwUhDuOp" is not active and cannot be executed
Even though an Error Trigger workflow has no external webhook URL or cron schedule of its own, n8n 1.76.1 refuses to execute it unless its Active toggle is turned on. After activating workflow yRGRaa9pgwUhDuOp for Run 2, the local receiver collected all 12 error reports: one for each of the 12 rejected requests among the 15 test cases (including {'workflow': 'gfl 2082 v2: timestamp + replay', 'execution': '21', 'lastNode': 'Stop: replayed', 'error': 'replayed signature', 'mode': 'webhook'}):

Inside workflow W1, the Code node separates structural header errors (HTTP 400) from cryptographic or clock-window failures (HTTP 401). Specifically, if X-GFL-Signature uses a semicolon delimiter instead of a comma (Case 9) or omits the t= timestamp key (Case 7), the Code node returns valid: false, status: 400 with the exact reason (malformed signature header or missing timestamp).
If the timestamp is more than 300 seconds behind or ahead of the container clock, tested at -600s (Case 3), -310s (Case 3c), +310s (Case 4c), and +600s (Case 4), the Code node returns valid: false, status: 401, reason: 'timestamp outside tolerance' without ever querying Postgres. Conversely, timestamps at -290s (Case 3b) and +290s (Case 4b) pass the window check and proceed to the database claim step. And because the signature is computed over t + "." + rawBody, taking the valid v1 digest from Case 1 and pairing it with a fresh timestamp (Case 10) fails the HMAC check with 401 signature mismatch:

When a request passes both the ±300s timestamp check and the constant-time HMAC check, the first If node routes the item to the Postgres claim node. Instead of running a separate SELECT followed by an INSERT (which creates a race window and requires two queries), the Postgres node runs a single Common Table Expression (CTE):
WITH ins AS (
INSERT INTO webhook_replay_guard (signature)
VALUES ($1)
ON CONFLICT (signature) DO NOTHING
RETURNING 1
)
SELECT COALESCE((SELECT 1 FROM ins), 0) AS claimed;
Wrapping INSERT ... ON CONFLICT (signature) DO NOTHING RETURNING 1 inside SELECT COALESCE(..., 0) AS claimed solves a common n8n workflow trap: when a plain INSERT ... RETURNING hits a conflict and returns zero rows, an n8n database node emits no output items by default, causing the downstream workflow branch to stop silently before reaching the Respond to Webhook node. With COALESCE, Postgres always returns exactly one row containing either {"claimed": 1} or {"claimed": 0}:

Comparing the measured response times across all 15 test cases in Run 2 shows the exact latency profile of each verification stage:
- Cold vs warm valid requests (
HTTP 200): Case 1 (the very first valid request hitting Postgres) completed in99 ms, while Case 2a (first send of the replay pair) completed in35 ms, Case 3b (-290s) in74 ms, and Case 4b (+290s) in71 ms. - Duplicate replay rejection (
HTTP 409): Case 2b (sending the exact same bytes and header as Case 2a a second time) hit thewebhook_replay_guardprimary key index, returnedclaimed = 0, replied withHTTP 409 Conflictin33 ms, and triggeredStop: replayed. - Code-node rejections (
HTTP 400&HTTP 401): Requests rejected inside the Code node before touching Postgres completed in27 msto76 ms(with boundary rejections3cand4cfinishing in27 ms).
Not covered by this test: several identical requests arriving at the exact same millisecond (to test concurrent locking under load), and computing the HMAC with n8n's built-in Crypto node instead of a Code node:

Not Tested
To keep the scope of these findings explicit, the following items were not tested in this local Docker Desktop lab:
- Real third-party cloud deliveries: All requests were signed on the host and sent with
curl --data-binaryusing dummy secrets; live webhook deliveries from Stripe, Shopify, or GitHub cloud servers were not tested. - Concurrent identical requests and Workflow Static Data: Case 2b was sent sequentially after Case 2a completed; simultaneous parallel deliveries and n8n's in-memory
$getWorkflowStaticData('global')were not tested. - n8n's built-in Header Auth credentials: The Webhook node was run with
Authentication: Noneso the Code node handled the signature check directly. - Nginx rate limiting in front of n8n: If you place Nginx in front of n8n in production, you can add edge rate limiting (such as
limit_req_zone $binary_remote_addr zone=n8n_webhooks:10m rate=10r/s;) to absorb volumetric floods before requests reach n8n, provided the proxy forwards the raw request body unmodified. - Reading secrets from n8n Credentials vs
$env, and n8n Cloud: All tests ran on self-hostedn8nio/n8n:1.76.1in Docker Desktop reading$env.WEBHOOK_SHARED_SECRET.

Use the lookup matrix below during staging and production debugging to map each runtime error message or unexpected HTTP status code (500, false-positive 200, 400, 401, or 409) directly to the exact configuration or Code-node fix verified in our lab:

Last reviewed: 2025-01-30. Tested on 2025-01-29 (KST) on n8nio/n8n:1.76.1 in Docker Desktop (Windows 11, Docker Engine 27.3.1, Compose v2.29.7) with requests signed on the host and sent with curl, using dummy secrets. The re-serialization and length-mismatch checks were run separately with Node.js crypto outside n8n. The timestamp window, replay table, If routing and error workflow were tested on 2025-01-30 (KST) with the same setup. Real Stripe, Shopify and GitHub deliveries were not tested.
3-Point Production Sign-Off Checklist
- Webhook Raw Body & Respond Mode: Confirm
Options → Raw Bodyis enabled on the Webhook node,Respondis set toUsing 'Respond to Webhook' Node, and the Code node hashesawait this.helpers.getBinaryDataBuffer(0, 'data'). - Container Sandbox Flags: Confirm
NODE_FUNCTION_ALLOW_BUILTIN=cryptoandN8N_BLOCK_ENV_ACCESS_IN_NODE=falseare active indocker-compose.ymland verified with both compact (32B) and spaced (35B) signed JSON payloads. - Timestamp Window, Replay Claim & Active Error Trigger: Confirm your signature binds
t + "." + rawBody(±300swindow), claimssignaturevia PostgreSQLON CONFLICT DO NOTHING, and has the companionError Triggerworkflow toggled to Active.
n8n Raw-Body HMAC SHA256 & Replay Window Edge Cases
Why does hashing JSON.stringify($json.body) fail valid Stripe or GitHub HMAC signatures in n8n?
Parsing JSON into a JavaScript object and re-serializing it strips original whitespace, trailing newlines, and key formatting that the sender signed. Enable Raw Body on the n8n Webhook node and compute crypto.createHmac('sha256', secret) over the raw binary request buffer.
Why did throwing new Error('401 Unauthorized') in an n8n Code node return HTTP 500 to the sender?
Uncaught exceptions inside a Code node abort the workflow execution and cause n8n to emit HTTP 500, prompting webhook providers to retry for hours. Route failed signature checks through an If node to a Respond to Webhook node configured with HTTP status code 401.
How do I block replay attacks alongside HMAC SHA256 verification in n8n?
Include the request timestamp in the signed payload, reject timestamps drifting more than 300 seconds from server time, and insert each unique delivery ID into a PostgreSQL table with a PRIMARY KEY constraint so duplicate deliveries fail immediately.
Run Prefilled Sizing Math & Download the 1-Page Runbook
Generate rate-limited TLS 1.3 reverse-proxy rules across Nginx, Caddy 2, and Traefik v3 for signed n8n webhook endpoints.