Verify Trigger.dev webhooks

The x-trigger-signature-hmacsha256 header lets you confirm that a delivery came from Trigger.dev and wasn't changed on the way. It holds the lowercase hex HMAC-SHA256 of the raw body, keyed with the webhook alert's secret, with no prefix and no timestamp. Trigger.dev's docs show only the SDK's webhooks.constructEvent(request, secret), so the header and algorithm here come from its open source SDK and delivery code.

These pages cover the alerts Trigger.dev sends to you. To receive other services' webhooks in your tasks, see Trigger.dev's Webhooks docs, a separate feature in public beta.

The facts

Signature header
x-trigger-signature-hmacsha256

Format: <lowercase hex>

Scheme
HMAC-SHA256
Signed material
{raw body}

The request body exactly as sent, with no timestamp or prefix added. Re-serialised JSON will not verify.

What to build
Recompute a digest over the raw body and compare
Key
shared secret

Trigger.dev webhook secret

Trigger.dev generates a secret for each webhook alert and shows it on the Alerts page. The whole string is the key, as UTF-8 bytes. Keep it in an environment variable, not in source code.

  • Where to find it: on the Alerts page when you create a webhook alert. Trigger.dev's example reads it from ALERT_WEBHOOK_SECRET.
  • Format: a plain string used as the key as it is. Don't base64-decode it or strip anything from it.
  • Scope: each webhook alert has its own secret, not one per project.
  • Rotation: Trigger.dev's docs describe no way to rotate it.

Source: Trigger.dev docs ↗

Code

express/src/index.js
javascript
require('dotenv').config({ quiet: true });
const express = require('express');
const crypto = require('crypto');

const app = express();

/**
 * Verify a Trigger.dev alert webhook signature.
 * The x-trigger-signature-hmacsha256 header is the bare hex HMAC-SHA256 of the
 * raw request body, keyed with the alert webhook secret as UTF-8.
 * @param {Buffer|string} rawBody - Raw request body
 * @param {string} signatureHeader - x-trigger-signature-hmacsha256 header value
 * @param {string} secret - Alert webhook secret
 * @returns {boolean}
 */
function verifyTriggerDevWebhook(rawBody, signatureHeader, secret) {
  if (!signatureHeader || !secret) {
    return false;
  }

  const expected = crypto
    .createHmac('sha256', secret)
    .update(rawBody)
    .digest('hex');

  // timingSafeEqual throws when lengths differ, so treat that as invalid
  try {
    return crypto.timingSafeEqual(
      Buffer.from(signatureHeader),
      Buffer.from(expected)
    );
  } catch {
    return false;
  }
}

// Read the raw body for any content type so the signature always verifies
app.post('/webhooks/trigger-dev',
  express.raw({ type: '*/*' }),
  (req, res) => {
    const signature = req.headers['x-trigger-signature-hmacsha256'];

    if (!signature) {
      return res.status(400).send('Missing signature header');
    }

    if (!verifyTriggerDevWebhook(req.body, signature, process.env.TRIGGER_DEV_WEBHOOK_SECRET)) {
      console.error('Trigger.dev webhook signature verification failed');
      return res.status(400).send('Invalid signature');
    }

    // Parse the payload only after verification
    let event;
    try {
      event = JSON.parse(req.body.toString());
    } catch {
      return res.status(400).send('Invalid JSON');
    }

    // The event type is in the body (there is no event-type header)
    switch (event.type) {
      case 'alert.run.failed': {
        const { run, task } = event.object;
        console.log(`Run ${run.id} of task ${task.id} failed:`, run.dashboardUrl);
        // Your code: Page on-call, open an incident, retry downstream work, etc.
        break;
      }

      case 'alert.deployment.success': {
        const { deployment, environment } = event.object;
        console.log(`Deployment ${deployment.version} succeeded in ${environment.type}`);
        // Your code: Post to Slack, update a status page, etc.
        break;
      }

      case 'alert.deployment.failed': {
        const { deployment, error } = event.object;
        console.log(`Deployment ${deployment.version} failed:`, error.message);
        // Your code: Notify the author, open a ticket, etc.
        break;
      }

      case 'alert.error': {
        const { classification, error } = event.object;
        console.log(`Error group alert (${classification}):`, error.message);
        // Your code: Create an issue for the new error group or regression
        break;
      }

      default:
        console.log(`Unhandled event type: ${event.type}`);
    }

    res.status(200).json({ received: true });
  }
);

app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

module.exports = { app, verifyTriggerDevWebhook };

if (require.main === module) {
  const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
    console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/trigger-dev`);
  });
}
nextjs/app/webhooks/trigger-dev/route.ts
typescript
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';

// Verify a Trigger.dev alert webhook: x-trigger-signature-hmacsha256 is the bare hex
// HMAC-SHA256 of the raw body, keyed with the alert webhook secret as UTF-8.
function verifySignature(rawBody: string, signature: string | null, secret: string | undefined): boolean {
  if (!signature || !secret) return false;

  const expected = crypto.createHmac('sha256', secret).update(rawBody).digest('hex');

  // timingSafeEqual throws when lengths differ, so treat that as invalid
  try {
    return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
  } catch {
    return false;
  }
}

export async function POST(request: NextRequest) {
  // Read the raw text body; parsing JSON first would change the signed bytes
  const rawBody = await request.text();
  const signature = request.headers.get('x-trigger-signature-hmacsha256');

  if (!signature) {
    return NextResponse.json({ error: 'Missing signature header' }, { status: 400 });
  }

  if (!verifySignature(rawBody, signature, process.env.TRIGGER_DEV_WEBHOOK_SECRET)) {
    return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
  }

  let event: any;
  try {
    event = JSON.parse(rawBody);
  } catch {
    return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
  }

  // The event type is in the body (there is no event-type header)
  switch (event.type) {
    case 'alert.run.failed':
      console.log(`Run ${event.object.run.id} of task ${event.object.task.id} failed`);
      // Your code: Page on-call, open an incident, etc.
      break;

    case 'alert.deployment.success':
      console.log(`Deployment ${event.object.deployment.version} succeeded`);
      // Your code: Post to Slack, update a status page, etc.
      break;

    case 'alert.deployment.failed':
      console.log(`Deployment ${event.object.deployment.version} failed:`, event.object.error.message);
      // Your code: Notify the author, open a ticket, etc.
      break;

    case 'alert.error':
      console.log(`Error group alert (${event.object.classification}):`, event.object.error.message);
      // Your code: Create an issue for the new error group or regression
      break;

    default:
      console.log(`Unhandled event type: ${event.type}`);
  }

  return NextResponse.json({ received: true });
}
fastapi/main.py
python
from __future__ import annotations

import hashlib
import hmac
import json
import os

from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request

load_dotenv()

app = FastAPI()

SIGNATURE_HEADER = "x-trigger-signature-hmacsha256"


def verify_trigger_dev_webhook(raw_body: bytes, signature_header: str | None, secret: str | None) -> bool:
    """The header is the bare hex HMAC-SHA256 of the raw body, keyed with the secret as UTF-8."""
    if not signature_header or not secret:
        return False
    expected = hmac.new(secret.encode("utf-8"), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(signature_header.encode(), expected.encode())


@app.post("/webhooks/trigger-dev")
async def trigger_dev_webhook(request: Request):
    # Use the raw bytes; re-serializing parsed JSON would change what was signed
    raw_body = await request.body()
    signature = request.headers.get(SIGNATURE_HEADER)

    if not signature:
        raise HTTPException(status_code=400, detail="Missing signature header")

    if not verify_trigger_dev_webhook(raw_body, signature, os.getenv("TRIGGER_DEV_WEBHOOK_SECRET")):
        raise HTTPException(status_code=400, detail="Invalid signature")

    try:
        event = json.loads(raw_body)
    except json.JSONDecodeError:
        raise HTTPException(status_code=400, detail="Invalid JSON")

    # The event type is in the body (there is no event-type header)
    event_type = event.get("type")
    obj = event.get("object", {})

    if event_type == "alert.run.failed":
        print(f"Run {obj['run']['id']} of task {obj['task']['id']} failed")
        # Your code: Page on-call, open an incident, etc.
    elif event_type == "alert.deployment.success":
        print(f"Deployment {obj['deployment']['version']} succeeded")
        # Your code: Post to Slack, update a status page, etc.
    elif event_type == "alert.deployment.failed":
        print(f"Deployment {obj['deployment']['version']} failed: {obj['error']['message']}")
        # Your code: Notify the author, open a ticket, etc.
    elif event_type == "alert.error":
        print(f"Error group alert ({obj['classification']}): {obj['error']['message']}")
        # Your code: Create an issue for the new error group or regression
    else:
        print(f"Unhandled event type: {event_type}")

    return {"received": True}


@app.get("/health")
async def health():
    return {"status": "ok"}

From hookdeck/webhook-skills ↗

Or install the Trigger.dev webhooks skill:

npx skills add hookdeck/webhook-skills --skill trigger-dev-webhooks

Common failures

Body parsed before verification

The signature covers the exact bytes. Read the raw body, or pass the untouched Request to the SDK, which consumes the body itself.

Wrong secret

Each webhook alert has its own secret. Use the one from that alert on the Alerts page, as a plain string, without base64-decoding it.

Expecting a prefix or base64

The header is bare lowercase hex. Code written for sha256=<hex> or a base64 digest never matches it.

The SDK rejects the alert type

constructEvent also validates the parsed body, so it throws WebhookError after a valid signature if type isn't in its list. Check the error message before you suspect the secret.

From Hookdeck's Trigger.dev guide

Let Event Gateway verify Trigger.dev signatures.

Event Gateway verifies the signature on each Trigger.dev delivery before it reaches your service, then queues it and retries failures on your schedule.

Not affiliated with Trigger.dev. Facts are compiled from public sources and linked inline.