n8n Webhook HMAC SHA256 Verification: Raw Body & Replay

21 min readBy Yun Sanghun (M. Yun)

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=crypto and N8N_BLOCK_ENV_ACCESS_IN_NODE=false in docker-compose.yml (alongside WEBHOOK_SHARED_SECRET) so the Code node can load Node's crypto module 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 (or 409 on replay) instead of HTTP 200 or HTTP 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) → Code node that hashes JSON.stringify($json.body) and throws new Error('401 Unauthorized: ...') on failure → no-op Business step.
  • Workflow B (raw-body version): Webhook (POST, Options → Raw Body on, Respond = Using 'Respond to Webhook' Node) → Code node that hashes the raw request bytes → Respond to Webhook node returning 200 or 401:
n8n v1.76.1 workflow editor showing active Webhook node configuration with HTTP Method POST, Respond set to Using Respond to Webhook Node, and Options Raw Body enabled to store request bytes in binary property data
Inspecting the active Webhook node configuration in n8nio/n8n:1.76.1 on Docker Desktop: enabling Options -> Raw Body preserves the exact incoming request bytes inside binary property data (32 bytes for compact JSON, 35 bytes for spaced JSON), while setting Respond to Using 'Respond to Webhook' Node lets the workflow return a real HTTP 401 on signature mismatch.
n8n webhook HMAC-SHA256 verification pipeline contrasting parsed JSON.stringify byte mutation and HTTP 500 leaks against Raw Body binary buffer hashing, 300-second replay window checks, and crypto.timingSafeEqual
Raw-Byte HMAC Verification Pipeline: Re-serializing parsed 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:

  1. Valid signature over compact JSON: {"event":"order.paid","id":1042} (32 bytes).
  2. Valid signature over the same JSON with spaces after the colons and comma: {"event": "order.paid", "id": 1042} (35 bytes).
  3. Signature computed with a second, unrelated secret over the 32-byte payload.
  4. Body changed by 1 byte after signing (1042 → 1043) while keeping the Case 1 signature header.
  5. X-Hub-Signature-256 header 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"}
Saved terminal test log on n8n 1.76.1 comparing Run 0 crypto disallowed, Run 1 access to env vars denied, and Run 2 five curl --data-binary test cases across the old JSON.stringify Code node versus the raw body and Respond to Webhook version
Saved test log across all three environment runs and five curl --data-binary test cases on n8n 1.76.1: after enabling NODE_FUNCTION_ALLOW_BUILTIN=crypto and N8N_BLOCK_ENV_ACCESS_IN_NODE=false in Run 2, the old JSON.stringify($json.body) code rejected validly signed 35-byte spaced JSON (Case 2) with HTTP 500, whereas the raw-body workflow passed both valid payloads (HTTP 200) and rejected Cases 3–5 with HTTP 401.

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 called JSON.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 to When Last Node Finishes, n8n responds to the caller with HTTP 500 and the body {"message":"Error in workflow"}, never an HTTP 401 status 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 returns undefined.
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
Execution ID#22 (23:53:48, 21ms | 7KB) in the local n8n editor for Case 2 (correctly signed 35-byte JSON with spaces): because n8n parsed the JSON body before the Code node ran, JSON.stringify($json.body) re-serialized it without spaces (32 bytes), causing Verify HMAC (post code) to throw 401 Unauthorized: Signature hash verification failed [line 29] and return HTTP 500 to curl.

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:

Side-by-side code editor comparing workflow_a_old_code.js (hashing JSON.stringify($json.body) at line 20 and throwing an uncaught Error at line 29) with sign_and_send_5_cases.py sending raw wire bytes via curl --data-binary
Comparing the legacy Workflow A Code node script (workflow_a_old_code.js, left) with the host-side Python wire signer (sign_and_send_5_cases.py, right): line 20 hashes JSON.stringify($json.body) instead of the raw wire buffer, while line 29 throws an uncaught JavaScript Error that n8n converts into an HTTP 500 {"message":"Error in workflow"} response.

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 via NODE_FUNCTION_ALLOW_BUILTIN=crypto.
  • Run 1 (added WEBHOOK_SHARED_SECRET and NODE_FUNCTION_ALLOW_BUILTIN=crypto): Every request then failed at the $env.WEBHOOK_SHARED_SECRET lookup with access to env vars denied. In n8n 1.76.1, reading $env inside a Code node is blocked unless you also set N8N_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
Reproducing the two sandbox errors that blocked every webhook request before Run 2: without NODE_FUNCTION_ALLOW_BUILTIN=crypto, require('crypto') fails at line 1 with Module 'crypto' is disallowed; without N8N_BLOCK_ENV_ACCESS_IN_NODE=false, reading $env.WEBHOOK_SHARED_SECRET fails with access to env vars denied (left), whereas setting both variables unblocks the Code node (right).

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:

Three-column decision matrix comparing n8n Webhook Respond modes: Immediately returning HTTP 200 on all requests, When Last Node Finishes returning HTTP 500 on errors, and Using Respond to Webhook Node returning HTTP 200 or HTTP 401
Empirical comparison of n8n's three Webhook Respond modes across Cases 1, 3, and 5: Respond = Immediately acknowledges every request with HTTP 200 {"message":"Workflow was started"} before the Code node runs (hiding signature failures from the sender), When Last Node Finishes leaks unhandled errors as HTTP 500, and Using 'Respond to Webhook' Node cleanly returns HTTP 200 or HTTP 401.

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 property data; in my test runs the 32-byte and 35-byte JSON payloads appeared there with mimeType: 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:

Node.js container output running /lab/hmac_reserialize.js showing verify raw: true for 35-byte spaced JSON, verify parsed: false for 32-byte re-serialized JSON, and ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH when buffer byte lengths differ
Running /lab/hmac_reserialize.js in a Node.js container outside n8n: hashing the 35-byte raw body ({"event": "order.paid", "id": 1042}) verifies true, hashing the 32-byte output of JSON.stringify(JSON.parse(raw)) verifies false, and calling crypto.timingSafeEqual on buffers of unequal byte length (sha256= vs bare ) throws ERR_CRYPTO_TIMING_SAFE_EQUAL_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:

n8n workflow editor canvas showing Workflow B with Webhook (Raw Body) connected to Verify HMAC (raw bytes) and Respond 200 or 401 alongside node parameter breakdown
Workflow B in the local n8n editor: Webhook (Raw Body) captures the unparsed request bytes into binary property data, Verify HMAC (raw bytes) computes the SHA-256 HMAC over this.helpers.getBinaryDataBuffer(0, 'data'), and Respond 200 or 401 returns {{ $json.valid ? 200 : 401 }} with the JSON verification reason.

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:

Side-by-side configuration editor showing docker-compose.yml for n8nio/n8n:1.76.1 with NODE_FUNCTION_ALLOW_BUILTIN=crypto and N8N_BLOCK_ENV_ACCESS_IN_NODE=false alongside verify_hmac_raw_bytes.js using getBinaryDataBuffer(0, 'data')
Complete working configuration for n8nio/n8n:1.76.1: docker-compose.yml (left) enables NODE_FUNCTION_ALLOW_BUILTIN=crypto and N8N_BLOCK_ENV_ACCESS_IN_NODE=false on 127.0.0.1:5679:5678, while verify_hmac_raw_bytes.js (right) hashes the raw binary buffer (data) and guards crypto.timingSafeEqual(a, b) with a.length === b.length.

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:

Split terminal comparison showing curl --data-binary requests to Workflow B returning HTTP 200 OK for both 32-byte compact and 35-byte spaced JSON on the left and HTTP 401 Unauthorized for wrong secret, 1-byte tamper, and missing header on the right
Direct curl -i --data-binary verification against Workflow B (/webhook/gfl-hmac-raw-body): hashing this.helpers.getBinaryDataBuffer(0, 'data') accepts both the 32-byte compact JSON and 35-byte spaced JSON with HTTP 200 OK (left), while rejecting a wrong secret, a 1-byte payload edit (1042 -> 1043), and a missing header with HTTP 401 Unauthorized (right).
  • 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 sends Stripe-Signature: t=<unix-seconds>,v1=<hex> where the HMAC is computed over <timestamp>.<raw_body>, while Shopify sends a Base64-encoded SHA-256 digest in X-Shopify-Hmac-SHA256 without a prefix (requiring .digest('base64') or comparing 32-byte raw buffers via Buffer.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.
Reference card comparing webhook HMAC-SHA256 formats across GitHub (X-Hub-Signature-256 sha256=<hex>), Stripe (Stripe-Signature t=<unix>,v1=<hex> over t.rawBody), and Shopify (X-Shopify-Hmac-SHA256 Base64)
Comparing webhook HMAC-SHA256 schemes across providers: GitHub signs rawBytes as sha256= in x-hub-signature-256 without a timestamp, Shopify signs rawBytes as Base64 in x-shopify-hmac-sha256, and Stripe-style headers (t=,v1=) bind the HMAC over t + "." + rawBytes so the receiver can enforce a timestamp window and replay table.

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>, where v1 is HMAC-SHA256(secret, t + "." + raw_body).
  • Code node: Reads the raw binary buffer, checks that the header uses , (not ;) and includes both t and v1, checks that Math.abs(now - t) <= 300 (a 300-second tolerance window), and verifies v1 with crypto.timingSafeEqual.
  • Replay table in Postgres: For requests that pass the Code node, a Postgres node runs an atomic INSERT ... ON CONFLICT (signature) DO NOTHING query that returns claimed = 1 on first delivery and claimed = 0 on a duplicate delivery.
  • Responses and error reporting: Valid first deliveries return HTTP 200; malformed headers return HTTP 400; bad signatures or out-of-window timestamps return HTTP 401; replayed signatures return HTTP 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):

Terminal log of 15 curl test cases against workflow W1 (Webhook Raw Body -> Code t,v1 + 300s window -> If -> Postgres claim -> If -> Respond) showing PASS 15 / 15 plus Run 1 inactive error workflow log and Run 2 receiver report
Complete 15-request verification log for workflow W1 (Webhook Raw Body -> Code t,v1 + 300s window -> If -> Postgres claim -> If -> Respond) on n8n 1.76.1: all 15 cases passed (200 OK for valid and ±290s requests, 409 Conflict for Case 2b replay, 401 for ±310s/±600s and tampered requests, 400 for malformed headers), plus the Run 1 inactive error workflow log and Run 2 receiver report.

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'}):

n8n v1.76.1 workflow editor showing 6-node replay-protected workflow W1 (gfl 2082 v2: timestamp + replay) connected to the active Error Trigger workflow and execution #21 Stop: replayed payload
Live n8nio/n8n:1.76.1 workflow editor showing gfl 2082 v2: timestamp + replay (W1) connected to the active Error Trigger workflow: rejected requests return 400, 401, or 409 via Respond to Webhook and then hit Stop And Error so the active error workflow posts a structured failure report to the local receiver.

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:

Side-by-side code editor showing verify_timestamp_and_hmac.js (validating t,v1 and ±300s tolerance window) and replay_claim.sql (INSERT INTO webhook_replay_guard ON CONFLICT DO NOTHING RETURNING 1 with COALESCE)
Implementation of workflow W1's two verification stages: verify_timestamp_and_hmac.js (left) validates the t=,v1= header format, enforces the ±300-second clock window, and verifies HMAC-SHA256(secret, t + "." + rawBody), while replay_claim.sql (right) atomically claims the signature in PostgreSQL via INSERT ... ON CONFLICT (signature) DO NOTHING and always returns claimed = 1 or 0.

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}:

Split comparison of PostgreSQL webhook_replay_guard query execution showing Case 2a first delivery returning claimed=1 and HTTP 200 OK in 35 ms versus Case 2b duplicate replay returning claimed=0 and HTTP 409 Conflict in 33 ms
Inspecting Case 2a versus Case 2b against the PostgreSQL webhook_replay_guard table: the first delivery inserts the signature key and returns claimed = 1 with HTTP 200 OK in 35 ms (left), whereas resending the identical signed payload hits ON CONFLICT DO NOTHING, returns claimed = 0 with HTTP 409 Conflict in 33 ms, and triggers Stop: replayed (right).

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 in 99 ms, while Case 2a (first send of the replay pair) completed in 35 ms, Case 3b (-290s) in 74 ms, and Case 4b (+290s) in 71 ms.
  • Duplicate replay rejection (HTTP 409): Case 2b (sending the exact same bytes and header as Case 2a a second time) hit the webhook_replay_guard primary key index, returned claimed = 0, replied with HTTP 409 Conflict in 33 ms, and triggered Stop: replayed.
  • Code-node rejections (HTTP 400 & HTTP 401): Requests rejected inside the Code node before touching Postgres completed in 27 ms to 76 ms (with boundary rejections 3c and 4c finishing in 27 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:

Dual-panel Matplotlib chart showing measured response latency (27 ms to 99 ms) across all 15 curl test cases color-coded by HTTP status (200, 409, 401, 400) on the left and the ±300-second timestamp acceptance window on the right
Measured response latency and HTTP status distribution across all 15 curl test cases on workflow W1 (left) and the ±300-second timestamp tolerance boundary (right): requests inside [-290s, +290s] pass on first delivery (200 OK, 35–99 ms), duplicate deliveries within the window return 409 Conflict (33 ms), and timestamps at ±310s or ±600s are rejected at the Code node with 401 Unauthorized (27–76 ms).

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-binary using 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: None so 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-hosted n8nio/n8n:1.76.1 in Docker Desktop reading $env.WEBHOOK_SHARED_SECRET.
Five-stage architecture diagram illustrating edge Nginx rate limiting, n8n Webhook Raw Body capture, Code node t,v1 and timingSafeEqual check, PostgreSQL ON CONFLICT replay claim, and Respond to Webhook plus active Error Trigger workflow
End-to-end webhook verification and replay-protection architecture combining edge rate limiting (limit_req_zone), n8n Webhook Raw Body binary buffering (binary.data), constant-time Code node HMAC + ±300s timestamp verification, PostgreSQL ON CONFLICT DO NOTHING signature claiming, and an active Error Trigger reporting workflow.

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:

Seven-row production error-to-fix lookup matrix mapping n8n webhook HMAC runtime errors and HTTP status codes (500, false 200, 400, 401, 409) to their verified configuration and code fixes
Complete error-to-fix lookup matrix for n8n 1.76.1 webhook HMAC verification and replay protection: mapping each runtime error message and HTTP status code (500, 200 false-positive, 400, 401, 409) to its exact environment flag, Raw Body binary buffer helper, Respond to Webhook setting, and PostgreSQL replay table query.

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

  1. Webhook Raw Body & Respond Mode: Confirm Options → Raw Body is enabled on the Webhook node, Respond is set to Using 'Respond to Webhook' Node, and the Code node hashes await this.helpers.getBinaryDataBuffer(0, 'data').
  2. Container Sandbox Flags: Confirm NODE_FUNCTION_ALLOW_BUILTIN=crypto and N8N_BLOCK_ENV_ACCESS_IN_NODE=false are active in docker-compose.yml and verified with both compact (32B) and spaced (35B) signed JSON payloads.
  3. Timestamp Window, Replay Claim & Active Error Trigger: Confirm your signature binds t + "." + rawBody (±300s window), claims signature via PostgreSQL ON CONFLICT DO NOTHING, and has the companion Error Trigger workflow 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.

100% Client-Side Utilities · Printable A4 Runbook

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.

Paired Prefilled Calculators & Vector PDF Checklist

Yun Sanghun (M. Yun) · Linux, Docker & AI Infrastructure Engineer