# How do I verify the signature of an email API webhook?

Compute an HMAC-SHA256 of the exact raw request body with your webhook secret, then compare it to the signature header using a constant-time function. Parse the JSON only after it matches. Never verify a re-serialised object, reject stale timestamps where the provider supplies one, and make handlers idempotent because retries and duplicates happen.

Updated 2026-11-13. By AISend (https://aisend.app).

## Why it happens

A webhook endpoint is a public URL. Anyone who learns it can POST a fake 'bounced' or 'complained' event and make your system suppress good customers, or a fake 'delivered' event and hide a real failure. The provider proves it is the sender by signing each request with a secret only the two of you know; your job is to recompute the signature and compare.

Most failures are not cryptographic. They are plumbing. How to recognise your case: the signature never matches although the secret is right. That almost always means you hashed something other than the exact bytes that were sent.

- A body parser ran first. Express's express.json() or a Next.js pages-router API route parses the body and gives you an object. JSON.stringify(object) does not reproduce the original bytes: key order, spacing and number formatting can differ, and the HMAC changes with a single byte.
- A middleware or proxy re-encoded the body (charset conversion, trimming a trailing newline, decompression).
- The secret has a hidden difference: a trailing newline from an env file, a prefix such as whsec_ that you stripped (or should not have), or a test secret used in production.
- The signature is in hex, you compared it as base64 (or the reverse), or you compared strings with === (works, but is not constant time).
- Your handler is slow and the provider retries, so you process the same event twice.

## How to fix it (the same pattern for any HMAC-signed webhook)

1. **Capture the raw body before any parser touches it.** In Express, mount express.raw({ type: 'application/json' }) on the webhook route (before any global express.json()), so req.body is a Buffer. In a Next.js App Router route handler, call await request.text() and parse the JSON yourself afterwards. In Flask, use request.get_data(). Whatever the framework, the goal is the identical byte sequence the provider hashed.
2. **Read the exact header name and the encoding, from the provider's docs.** Each provider differs: the header name, whether the digest is hex or base64, whether there is a version prefix such as sha256=, and whether a timestamp is part of what is signed. Do not guess; copy the documented rule.
3. **Compute the HMAC with your secret and compare in constant time.** Use HMAC-SHA256 with the whole secret string as the key (including any prefix the provider gave you, unless their docs say to strip it). Compare with a constant-time function: crypto.timingSafeEqual in Node (it throws if the two buffers differ in length, so check the length first) or hmac.compare_digest in Python. A normal string comparison can leak how many leading characters matched.

```
// Node.js (works in Express with express.raw, or in Next.js with request.text())
import crypto from "node:crypto";

export function verifySignature(rawBody, signatureHex, secret) {
  if (typeof signatureHex !== "string") return false;
  const expected = crypto.createHmac("sha256", secret).update(rawBody).digest(); // Buffer
  const given = Buffer.from(signatureHex, "hex");
  if (given.length !== expected.length) return false; // timingSafeEqual throws on unequal lengths
  return crypto.timingSafeEqual(given, expected);
}
```

4. **Wire it into the framework with the raw body.** Verify first, reject with 401 on mismatch, and only then parse. Return 2xx quickly after verifying and put slow work on a queue; providers treat slow responses and errors as failures and retry.

```
// Express
import express from "express";
const app = express();

app.post("/webhooks/email", express.raw({ type: "application/json" }), (req, res) => {
  const ok = verifySignature(req.body, req.get("x-webhook-signature"), process.env.WEBHOOK_SECRET);
  if (!ok) return res.status(401).send("invalid signature");
  const event = JSON.parse(req.body.toString("utf8"));
  queue.add("email-event", event); // do the slow work elsewhere
  res.sendStatus(200);
});

// Next.js App Router: app/api/webhooks/email/route.ts
export async function POST(request) {
  const rawBody = await request.text(); // not request.json()
  if (!verifySignature(rawBody, request.headers.get("x-webhook-signature"), process.env.WEBHOOK_SECRET)) {
    return new Response("invalid signature", { status: 401 });
  }
  const event = JSON.parse(rawBody);
  // enqueue and return
  return new Response("ok");
}
```

5. **Python equivalent.** Same rule in Python: hash the raw bytes, compare with compare_digest.

```
import hashlib, hmac, os
from flask import Flask, request, abort

app = Flask(__name__)

@app.post("/webhooks/email")
def email_webhook():
    raw = request.get_data()                      # bytes exactly as received
    given = request.headers.get("X-Webhook-Signature", "")
    expected = hmac.new(os.environ["WEBHOOK_SECRET"].encode(), raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(given, expected):
        abort(401)
    event = request.get_json(force=True)
    # enqueue and return quickly
    return "", 200
```

6. **Defend against replays.** A valid signature on a captured request stays valid forever unless something in the signed data expires. If the provider signs a timestamp, reject requests older than a few minutes. If it does not, use a timestamp that is inside the signed body when there is one, and still make handlers idempotent so a replayed event is harmless.
7. **Make the handler idempotent and expect retries.** Providers retry on timeouts and 5xx responses, and some deliver the same event more than once. Store a unique key (the provider's event id, or the email id plus event type for status events) and skip events you have already processed. A bounce handler that adds an address to a suppression list is naturally idempotent; a handler that increments a counter is not.
8. **Rotate the secret without dropping events.** Keep the secret in a secret manager, never in the repository. To rotate, accept either the old or the new secret for a short overlap if your provider supports two secrets, otherwise rotate during a quiet period and watch for 401s on your side.

## When to use AISend

AISend signs every webhook delivery, and this is exactly what the sender does. The signature is the lowercase hex of HMAC-SHA256, keyed with the webhook's secret (a string starting with whsec_, shown when you create the webhook; use the whole string including the prefix), computed over the raw JSON request body. It is sent in the X-Webhook-Signature header (header names are case-insensitive). The delivery also carries Content-Type: application/json and X-Webhook-Id, the id of the webhook endpoint (not of the event). There is no signature prefix such as sha256= and no signed timestamp header, so the Node and Python snippets above work unchanged.

The body is JSON of the form { type, email_id, data, created_at }. type is the event name you subscribed to (sent, delivered, bounced, complained, failed, or * for all), email_id identifies the email, and created_at is generated when the delivery attempt is made, so a retry carries a new created_at and a new signature. Because created_at is inside the signed body, you can reject a request whose created_at is far from your clock, and use email_id plus type as your idempotency key for status events.

Delivery behaviour, from the worker code: a 10-second timeout, success on any 2xx response, retry with exponential backoff (up to five attempts, starting at two seconds) after a 5xx response or a network error, no retry after a 4xx, and automatic deactivation of the webhook after five consecutive failed deliveries (you can re-enable it in the dashboard). A retry can re-deliver to endpoints that already received the event, so idempotent handlers are required, not optional.

Sending to your recipients needs a paid plan; a free account can send 10 test emails to its own verified address. It is a young service with no uptime SLA, so build your handler to tolerate delays and duplicates. If you need a signed timestamp header or versioned secrets, AISend does not provide them today, and a provider that does would be the better fit. The MCP tools do not manage webhooks; create them with the REST API or the dashboard.

## Copy-paste prompt for an AI assistant connected to AISend

```
Assign to AISend: help me debug why my webhook receiver rejects every AISend event. Use list_emails with limit 10 to show my recent emails and their status, and get_email_status for the most recent bounced or delivered one so I can compare it with what my endpoint received. Do not send, resend or change anything. Show me what you did so I can approve any next step, and remind me that the signature is checked against the raw body, not the parsed JSON.
```

## Frequently asked questions

### Why does my HMAC never match even though the secret is correct?

You are almost certainly hashing something other than the exact bytes sent, usually a parsed and re-serialised JSON object. Read the raw body (express.raw, request.text(), request.get_data()) and verify before parsing.

### Why use timingSafeEqual instead of ===?

A normal comparison can stop at the first differing character, which leaks timing information an attacker can use to guess a signature byte by byte. A constant-time comparison takes the same time either way. In Node, check the lengths first because timingSafeEqual throws on unequal lengths.

### What is the AISend signature header and encoding?

X-Webhook-Signature, containing the lowercase hex of an HMAC-SHA256 over the raw JSON body, keyed with the webhook's whsec_ secret. There is no sha256= prefix and no separate timestamp header.

### Do I need to handle duplicate webhook events?

Yes. Providers retry on timeouts and server errors and may deliver an event more than once, and AISend retries can re-deliver to endpoints that already got the event. Store an event key and skip repeats.

### What should my endpoint return?

A 2xx status as soon as the signature checks out, with slow work moved to a queue. For AISend a non-2xx response counts as a failure, and five consecutive failures deactivate the webhook.

## Sources

- [Node.js documentation: crypto.timingSafeEqual](https://nodejs.org/api/crypto.html) (checked 2026-11-13)
- [Next.js documentation: Route Handlers (request.text)](https://nextjs.org/docs/app/api-reference/file-conventions/route) (checked 2026-11-13)

## Related

- https://aisend.app/blog/webhook-email-tracking
- https://aisend.app/solutions/check-ai-agent-email-delivered
- https://aisend.app/solutions/email-api-429-rate-limit
- https://aisend.app/blog/email-bounce-handling-guide
- https://aisend.app/docs

Human page: https://aisend.app/solutions/verify-email-webhook-signature
All problems and solutions: https://aisend.app/solutions (machine-readable: https://aisend.app/solutions.json)
