Skip to content

Verify Mailgun webhooks

Verify that a webhook really came from Mailgun before acting on it.

Identifier 'mailgun'
Import import { verifyMailgun } from 'verihook/mailgun'
Headers (signature is in the body)
Signature HMAC-SHA256 of <timestamp><token>, hex-encoded, in the body’s signature object (JSON) or form fields.
Replay window 300 seconds (options.tolerance)
result.eventType event-data.event, e.g. delivered

The HTTP webhook signing key: in the Mailgun dashboard, open Sending → Webhooks (or Settings → API Security). It is not your API key.

Store it in an environment variable (MAILGUN_WEBHOOK_SIGNING_KEY below) and never commit it.

import { verifyMailgun } from 'verihook/mailgun';
export async function POST(request: Request) {
const result = await verifyMailgun(request, process.env.MAILGUN_WEBHOOK_SIGNING_KEY!);
if (!result.valid) {
console.warn(result.code, result.reason, result.hint);
return new Response('Invalid signature', { status: 401 });
}
console.log(result.eventType, result.event);
return Response.json({ received: true });
}

request can be a Fetch Request or { headers, body, url? } with the raw body. verifyWebhook('mailgun', request, secret) from verihook does the same. Read why the raw body matters if verification fails behind a body parser.

app/api/webhooks/mailgun/route.ts
import { createWebhookHandler } from 'verihook/next';
export const POST = createWebhookHandler('mailgun', process.env.MAILGUN_WEBHOOK_SIGNING_KEY!, async (payload, result) => {
// Runs only for a valid signature
console.log(result.eventType, result.event);
});

Each adapter responds 401 to an invalid signature, 413 to a body over maxBodySize (2 MB by default) and 200 to a duplicate when you pass a dedupeStore.

  • The signature authenticates the sender but doesn’t cover the event data. With a dedupe store, the token is used as the event ID, as Mailgun recommends.

signWebhook from verihook/testing builds a correctly signed Mailgun request for your tests:

import { signWebhook } from 'verihook/testing';
import { verifyMailgun } from 'verihook/mailgun';
const hook = await signWebhook('mailgun', {
secret: 'mailgun_signing_key',
payload: { id: 'evt_test' },
});
const result = await verifyMailgun(
{ headers: hook.headers, body: hook.body, url: hook.url },
hook.secret,
);
// result.valid === true

From the command line, npx verihook simulate mailgun --url http://localhost:3000/webhooks/mailgun sends one to your local server.

See Testing your handlers for supertest and Fetch Request examples.

Failed results carry a code and often a hint with the likely cause. See Troubleshooting for each error code.

Mailgun’s webhook documentation