# Verify Prefect webhooks

Prefect doesn't sign Custom Webhook requests, so there's no signature to check. Add a secret header to the block and compare its whole value on your endpoint in constant time. That shows the sender knows the secret, but it doesn't cover the body or stop a replayed request.

These pages cover requests a Prefect automation sends through a Custom Webhook notification block. To send events into Prefect, see [Prefect Cloud webhooks](https://www.prefect.io/docs/v3/concepts/webhooks). The separate [Call a webhook](https://www.prefect.io/docs/v3/concepts/automations#actions) action uses a different block and isn't covered here.

Agent skill: `npx skills add hookdeck/webhook-skills --skill prefect-webhooks` ([details](https://hookdeck.com/webhooks/prefect/skill))

> Independent reference generated from hookdeck/webhook-registry (commit ff7f882, 20 Nov 2026). [Prefect's official docs](https://github.com/PrefectHQ/prefect/blob/main/src/prefect/blocks/notifications.py).

[Overview](https://hookdeck.com/webhooks/prefect) · [MCP events](https://hookdeck.com/webhooks/prefect/mcp-events) · [Verify signatures](https://hookdeck.com/webhooks/prefect/verify) · [Production guide](https://hookdeck.com/webhooks/prefect/guide-duplicates-ordering-retries-timeouts) · [Agent skill](https://hookdeck.com/webhooks/prefect/skill)

## The facts

| Fact | Value | Source |
|---|---|---|
| Signature header | `None (unsigned)` | [Prefect docs](https://github.com/PrefectHQ/prefect/blob/main/src/prefect/blocks/notifications.py) |
| What to build | `Compare the header you added with your stored value, byte for byte` | [Prefect docs](https://github.com/PrefectHQ/prefect/blob/main/src/prefect/blocks/notifications.py) |
| Key | `shared secret` | [Prefect docs](https://github.com/PrefectHQ/prefect/blob/main/src/prefect/blocks/notifications.py) |

## Prefect webhook secret

There's no Prefect-issued secret. You choose the header and its value on the Custom Webhook block, and storing the value in `secrets` keeps it out of the block's plain configuration. Keep it in an environment variable, not in source code.

- Generate a long random value yourself, for example with `openssl rand -hex 32`.
- Add it to the block under **Custom Secret Values** (`secrets`), then reference its key in **Headers**, for example `{{webhook_secret}}`.
- Set per block, so every automation that uses the block sends the same value.
- Prefect substitutes the value before sending, so compare the rendered value, including any prefix such as `Bearer ` that you typed around the placeholder.
- Prefect documents no rotation flow or test and live values. To rotate, change the block and your receiver together.

Source: [Prefect docs](https://github.com/PrefectHQ/prefect/blob/main/src/prefect/blocks/notifications.py)

## Code

### Express

From [webhook-skills: skills/prefect-webhooks/examples/express/src/index.js](https://github.com/hookdeck/webhook-skills/blob/556a89753e3e66e85d2a3ce50558e95b96c08571/skills/prefect-webhooks/examples/express/src/index.js)

```javascript
// Generated with: prefect-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const crypto = require('crypto');
const express = require('express');

const app = express();

/**
 * Constant-time string comparison. Hashing both sides first gives equal-length
 * buffers, so timingSafeEqual never throws and the secret's length isn't leaked.
 */
function safeEqual(a, b) {
  const ha = crypto.createHash('sha256').update(String(a)).digest();
  const hb = crypto.createHash('sha256').update(String(b)).digest();
  return crypto.timingSafeEqual(ha, hb);
}

/**
 * Prefect does not sign Custom Webhook notifications. You add a secret header in the
 * block's headers; the header name is yours, so it comes from PREFECT_WEBHOOK_HEADER
 * (default "Authorization"). Compare the WHOLE value with PREFECT_WEBHOOK_SECRET:
 * do not strip a "Bearer " prefix.
 */
function verifyPrefectRequest(
  headers,
  secret = process.env.PREFECT_WEBHOOK_SECRET,
  headerName = process.env.PREFECT_WEBHOOK_HEADER || 'Authorization'
) {
  if (!secret) return false; // never accept when unconfigured
  const received = headers[headerName.toLowerCase()]; // Node lowercases header names
  return Boolean(received) && safeEqual(received, secret);
}

/**
 * Prefect adds no event field: the body is whatever json_data / form_data template you
 * configured on the block, with {{subject}}, {{body}} and {{name}} substituted. This
 * example assumes an illustrative template:
 *   {"subject": "{{subject}}", "body": "{{body}}", "name": "{{name}}"}
 */
function handleNotification(payload) {
  const { subject, body, name } = payload;
  console.log(`Prefect notification from "${name}": ${subject}`);
  console.log(body);
  // Your code: route by your own convention, e.g. match subject text or add a field to the template
}

// Parse only after the credential check. Empty bodies (e.g. GET) are valid.
function parseBody(buf, contentType = '') {
  const text = Buffer.isBuffer(buf) ? buf.toString('utf8') : '';
  if (!text.trim()) return {};
  if (contentType.includes('application/x-www-form-urlencoded')) {
    return Object.fromEntries(new URLSearchParams(text));
  }
  const parsed = JSON.parse(text);
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
    throw new Error('Expected a JSON object');
  }
  return parsed;
}

// The block's method is configurable (POST by default), so accept all of these.
// Read the body raw (any content type) so the request is authenticated before parsing.
function webhookRoute(req, res) {
  if (!verifyPrefectRequest(req.headers)) {
    return res.status(401).json({ error: 'Invalid or missing webhook credential' });
  }

  let payload;
  try {
    payload = parseBody(req.body, req.headers['content-type']);
  } catch {
    return res.status(400).json({ error: 'Invalid body' });
  }

  try {
    handleNotification(payload);
  } catch (err) {
    console.error('Error handling Prefect notification:', err);
    return res.status(500).json({ error: 'Handler error' });
  }

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

const raw = express.raw({ type: '*/*' });
app.route('/webhooks/prefect')
  .post(raw, webhookRoute)
  .put(raw, webhookRoute)
  .patch(raw, webhookRoute)
  .get(raw, webhookRoute);

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

module.exports = app;
module.exports.verifyPrefectRequest = verifyPrefectRequest;

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: http://localhost:${PORT}/webhooks/prefect (POST, PUT, PATCH, GET)`);
  });
}
```

### Next.js

From [webhook-skills: skills/prefect-webhooks/examples/nextjs/app/webhooks/prefect/route.ts](https://github.com/hookdeck/webhook-skills/blob/556a89753e3e66e85d2a3ce50558e95b96c08571/skills/prefect-webhooks/examples/nextjs/app/webhooks/prefect/route.ts)

```typescript
// Generated with: prefect-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifyPrefectRequest } from '../../../lib/verify-prefect';

// Prefect adds no event field: the body is whatever json_data / form_data template you
// configured on the block, with {{subject}}, {{body}} and {{name}} substituted. This
// example assumes an illustrative template:
//   {"subject": "{{subject}}", "body": "{{body}}", "name": "{{name}}"}
interface PrefectNotification {
  subject?: string;
  body?: string;
  name?: string;
  [key: string]: unknown;
}

function handleNotification(payload: PrefectNotification): void {
  const { subject, body, name } = payload;
  console.log(`Prefect notification from "${name}": ${subject}`);
  console.log(body);
  // Your code: route by your own convention, e.g. match subject text or add a field to the template
}

// Parse only after the credential check. Empty bodies (e.g. GET) are valid.
function parseBody(text: string, contentType: string): PrefectNotification {
  if (!text.trim()) return {};
  if (contentType.includes('application/x-www-form-urlencoded')) {
    return Object.fromEntries(new URLSearchParams(text));
  }
  const parsed = JSON.parse(text);
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
    throw new Error('Expected a JSON object');
  }
  return parsed;
}

// The block's method is configurable (POST by default), so accept all of these.
async function handle(request: NextRequest) {
  // Authenticate before reading or parsing the body.
  if (!verifyPrefectRequest(request.headers)) {
    return NextResponse.json({ error: 'Invalid or missing webhook credential' }, { status: 401 });
  }

  let payload: PrefectNotification;
  try {
    // Read as text so any content type is accepted.
    payload = parseBody(await request.text(), request.headers.get('content-type') ?? '');
  } catch {
    return NextResponse.json({ error: 'Invalid body' }, { status: 400 });
  }

  try {
    handleNotification(payload);
  } catch (err) {
    console.error('Error handling Prefect notification:', err);
    return NextResponse.json({ error: 'Handler error' }, { status: 500 });
  }

  return NextResponse.json({ received: true });
}

export const POST = handle;
export const PUT = handle;
export const PATCH = handle;
export const GET = handle;
```

### FastAPI

From [webhook-skills: skills/prefect-webhooks/examples/fastapi/main.py](https://github.com/hookdeck/webhook-skills/blob/556a89753e3e66e85d2a3ce50558e95b96c08571/skills/prefect-webhooks/examples/fastapi/main.py)

```python
# Generated with: prefect-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hashlib
import hmac
import json
import os
from urllib.parse import parse_qsl

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

load_dotenv()

app = FastAPI()


def safe_equal(a: str, b: str) -> bool:
    """Constant-time comparison: encode both sides to bytes (str would raise on
    non-ASCII), then compare equal-length SHA-256 digests."""
    return hmac.compare_digest(
        hashlib.sha256(a.encode("utf-8")).digest(),
        hashlib.sha256(b.encode("utf-8")).digest(),
    )


def verify_prefect_request(headers, secret=None, header_name=None) -> bool:
    """Prefect does not sign Custom Webhook notifications. You add a secret header in the
    block's headers; the header name is yours, so it comes from PREFECT_WEBHOOK_HEADER
    (default "Authorization"). Compare the WHOLE value with PREFECT_WEBHOOK_SECRET:
    do not strip a "Bearer " prefix.
    """
    secret = secret if secret is not None else os.environ.get("PREFECT_WEBHOOK_SECRET")
    header_name = header_name or os.environ.get("PREFECT_WEBHOOK_HEADER") or "Authorization"
    if not secret:
        return False  # never accept when unconfigured
    received = headers.get(header_name)  # Starlette headers are case-insensitive
    return bool(received) and safe_equal(received, secret)


async def require_prefect_credential(request: Request) -> None:
    """FastAPI dependency: reject the request before the body is parsed."""
    if not verify_prefect_request(request.headers):
        raise HTTPException(status_code=401, detail="Invalid or missing webhook credential")


def handle_notification(payload: dict) -> None:
    """Prefect adds no event field: the body is whatever json_data / form_data template you
    configured on the block, with {{subject}}, {{body}} and {{name}} substituted. This
    example assumes an illustrative template:
      {"subject": "{{subject}}", "body": "{{body}}", "name": "{{name}}"}
    """
    print(f'Prefect notification from "{payload.get("name")}": {payload.get("subject")}')
    print(payload.get("body"))
    # Your code: route by your own convention, e.g. match subject text or add a field to the template


def parse_body(raw_body: bytes, content_type: str) -> dict:
    """Parse only after the credential check. Empty bodies (e.g. GET) are valid."""
    text = raw_body.decode("utf-8")
    if not text.strip():
        return {}
    if "application/x-www-form-urlencoded" in content_type:
        return dict(parse_qsl(text))
    parsed = json.loads(text)
    if not isinstance(parsed, dict):
        raise ValueError("Expected a JSON object")
    return parsed


# The block's method is configurable (POST by default), so accept all of these.
@app.api_route(
    "/webhooks/prefect",
    methods=["POST", "PUT", "PATCH", "GET"],
    dependencies=[Depends(require_prefect_credential)],
)
async def prefect_webhook(request: Request):
    # Read the raw body so any content type is accepted.
    raw_body = await request.body()

    try:
        payload = parse_body(raw_body, request.headers.get("content-type", ""))
    except ValueError:  # includes JSONDecodeError and UnicodeDecodeError
        raise HTTPException(status_code=400, detail="Invalid body")

    try:
        handle_notification(payload)
    except Exception as err:  # noqa: BLE001
        print(f"Error handling Prefect notification: {err}")
        raise HTTPException(status_code=500, detail="Handler error")

    return {"received": True}


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


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)
```

Or install the Prefect webhooks skill: `npx skills add hookdeck/webhook-skills --skill prefect-webhooks`

## Common failures

- **The block has no secret header.** Headers are optional, and Prefect's own Telegram example sets none. A block without one sends nothing to compare, so add the header under **Headers**.
- **You stored the placeholder.** Prefect sends the rendered value. Compare against the secret itself, not the `{{webhook_secret}}` text you typed in the block.
- **The compared value is missing a prefix.** If the block's header is `Bearer {{webhook_secret}}`, the value sent is `Bearer ` plus the secret. Compare the whole string.
- **The secret changed in only one place.** Each block holds its own secret, so change it on every block that targets the endpoint and in your handler together.

From [Hookdeck's Prefect guide](https://hookdeck.com/webhooks/prefect/guide-duplicates-ordering-retries-timeouts).

---

Not affiliated with Prefect. Facts are compiled from public sources and linked inline. [View as JSON](https://hookdeck.com/webhooks/prefect.json) · [Report a correction](https://hookdeck.com/contact)
