# Verify OpenGen webhooks in Next.js App Router

> OpenGen delivers per-request generation lifecycle webhooks signed with Ed25519 keys published at GET /.well-known/webhook-jwks.json. Read the exact raw UTF-8 request body in a Next.js App Router Route Handler, validate all five X-OpenGen-Webhook headers and a 300-second replay window, verify the 128-character hex Ed25519 signature via node crypto, deduplicate by envelope id, and fetch private outputs separately via GET /v1/generations/{jobId}.

## Agent Prompt

```text
Implement a production OpenGen webhook receiver in my Next.js App Router project against https://opengen.dev:
1. Create app/api/webhooks/opengen/route.ts with export const runtime = 'nodejs'.
2. Read the exact raw UTF-8 body via await request.text() BEFORE JSON.parse().
3. Require all five headers: X-OpenGen-Webhook-Request-Id, X-OpenGen-Webhook-Workspace-Id, X-OpenGen-Webhook-Timestamp, X-OpenGen-Webhook-Key-Id, and X-OpenGen-Webhook-Signature.
4. Enforce a +/-300-second timestamp replay window and a 128-character lowercase hex Ed25519 signature format.
5. Fetch and cache https://opengen.dev/.well-known/webhook-jwks.json (forcing one refresh when an unknown kid appears during key rotation) and verify the Ed25519 signature over `${requestId}\n${workspaceId}\n${timestamp}\n${sha256Hex(rawBody)}` using node:crypto.
6. Require a configured OPENGEN_WORKSPACE_ID (fail closed with 500 if unset), confirm envelope.id === requestId, envelope.workspaceId === workspaceId, and envelope.workspaceId === OPENGEN_WORKSPACE_ID (return 403 on mismatch), deduplicate transactionally by envelope.id, and on generation.delivery_ready fetch fresh private output links from GET https://opengen.dev/v1/generations/{jobId}.
```

OpenGen delivers generation lifecycle events to a **per-request `webhookUrl`** supplied directly on `POST /v1/generations` (or MCP `generate`). Every delivery is signed asymmetrically with **Ed25519** (`OKP` / `EdDSA`) public keys published unauthenticated at `GET https://opengen.dev/.well-known/webhook-jwks.json`, so your Next.js App Router handler needs zero shared HMAC secrets.

## 1. Pass `webhookUrl` and `webhookEvents` when submitting a job

Attach `webhookUrl` (must be a public HTTPS URL on port `443` with no embedded credentials or `#fragment`) and an optional `webhookEvents` array on `POST /v1/generations`.

Supported `webhookEvents` values:

- `generation.started`
- `generation.completed` (default)
- `generation.failed` (default)
- `generation.cancelled` (default)
- `generation.delivery_ready` (recommended when downloading private outputs)

```bash tab="cURL"
set -eu
umask 077

RAW_UUID="$(uuidgen)"
[ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; }
IDEMPOTENCY_KEY="wh-job-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')"
SUBMISSION_JSON="$(cat <<'JSON' | jq --arg key "$IDEMPOTENCY_KEY" '{ idempotencyKey: $key, payload: . }'
{
  "modelId": "openai/gpt-image-2",
  "operation": "text-to-image",
  "input": {
    "prompt": "A brass compass on linen, soft studio light",
    "resolution": "1K",
    "quality": "low",
    "outputFormat": "png"
  },
  "routeId": "openai-undisclosed/openai-gpt-image-2",
  "billing": "managed",
  "maxCostMicros": 50000,
  "webhookUrl": "https://app.example.com/api/webhooks/opengen",
  "webhookEvents": [
    "generation.completed",
    "generation.failed",
    "generation.delivery_ready"
  ]
}
JSON
)"

# Atomically claim the submission record with both key and exact payload (refuses overwrite/races)
(set -C; printf '%s\n' "$SUBMISSION_JSON" > webhook-job-submission.json)

jq '.payload' webhook-job-submission.json | curl --fail-with-body \
  -X POST "https://opengen.dev/v1/generations" \
  -H "Authorization: Bearer $OPENGEN_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $IDEMPOTENCY_KEY" \
  --data-binary @- > webhook-job-receipt.json
```

```ts tab="TypeScript"
import { randomUUID } from 'node:crypto';
import { writeFile } from 'node:fs/promises';

const origin = process.env.OPENGEN_API_URL ?? 'https://opengen.dev';
const payload = {
  modelId: 'openai/gpt-image-2',
  operation: 'text-to-image',
  input: {
    prompt: 'A brass compass on linen, soft studio light',
    resolution: '1K',
    quality: 'low',
    outputFormat: 'png',
  },
  routeId: 'openai-undisclosed/openai-gpt-image-2',
  billing: 'managed',
  maxCostMicros: 50000,
  webhookUrl: 'https://app.example.com/api/webhooks/opengen',
  webhookEvents: ['generation.completed', 'generation.failed', 'generation.delivery_ready'],
} as const;

// Save idempotencyKey + exact payload exclusively (flag: 'wx' refuses to overwrite an unresolved submission).
const idempotencyKey = `wh-job-${randomUUID()}`;
await writeFile(
  'webhook-job-submission.json',
  JSON.stringify({ idempotencyKey, payload }, null, 2),
  { mode: 0o600, flag: 'wx' },
);

const res = await fetch(`${origin}/v1/generations`, {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.OPENGEN_API_KEY}`,
    'Content-Type': 'application/json',
    'Idempotency-Key': idempotencyKey,
  },
  body: JSON.stringify(payload),
});
if (!res.ok) throw new Error(`Generation submission failed (${res.status}): ${await res.text()}`);
const job = await res.json();
console.log(job.id);
```

```python tab="Python"
import json
import os
import uuid
import httpx

origin = os.environ.get("OPENGEN_API_URL", "https://opengen.dev")
payload = {
    "modelId": "openai/gpt-image-2",
    "operation": "text-to-image",
    "input": {
        "prompt": "A brass compass on linen, soft studio light",
        "resolution": "1K",
        "quality": "low",
        "outputFormat": "png",
    },
    "routeId": "openai-undisclosed/openai-gpt-image-2",
    "billing": "managed",
    "maxCostMicros": 50000,
    "webhookUrl": "https://app.example.com/api/webhooks/opengen",
    "webhookEvents": [
        "generation.completed",
        "generation.failed",
        "generation.delivery_ready",
    ],
}

# Persist idempotency_key + exact payload exclusively (O_EXCL refuses to overwrite an unresolved submission).
idempotency_key = f"wh-job-{uuid.uuid4()}"
fd = os.open("webhook-job-submission.json", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as handle:
    json.dump({"idempotencyKey": idempotency_key, "payload": payload}, handle, indent=2)

with httpx.Client(timeout=30.0) as client:
    job = client.post(
        f"{origin}/v1/generations",
        headers={
            "Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}",
            "Idempotency-Key": idempotency_key,
        },
        json=payload,
    ).raise_for_status().json()
    print(job["id"])
```

```json tab="MCP"
{
  "tool": "generate",
  "arguments": {
    "idempotencyKey": "wh-job-example-001",
    "modelId": "openai/gpt-image-2",
    "operation": "text-to-image",
    "input": {
      "prompt": "A brass compass on linen, soft studio light",
      "resolution": "1K",
      "quality": "low",
      "outputFormat": "png"
    },
    "routeId": "openai-undisclosed/openai-gpt-image-2",
    "billing": "managed",
    "maxCostMicros": 50000,
    "webhookUrl": "https://app.example.com/api/webhooks/opengen",
    "webhookEvents": ["generation.completed", "generation.failed", "generation.delivery_ready"]
  }
}
```

```bash tab="CLI"
set -eu
umask 077

RAW_UUID="$(uuidgen)"
[ -n "$RAW_UUID" ] || { echo "uuidgen failed" >&2; exit 1; }
IDEMPOTENCY_KEY="wh-job-$(printf '%s' "$RAW_UUID" | tr '[:upper:]' '[:lower:]')"
SUBMISSION_JSON="$(cat <<'JSON' | jq --arg key "$IDEMPOTENCY_KEY" '{ idempotencyKey: $key, payload: . }'
{
  "modelId": "openai/gpt-image-2",
  "operation": "text-to-image",
  "input": {
    "prompt": "A brass compass on linen, soft studio light",
    "resolution": "1K",
    "quality": "low",
    "outputFormat": "png"
  },
  "routeId": "openai-undisclosed/openai-gpt-image-2",
  "billing": "managed",
  "maxCostMicros": 50000,
  "webhookUrl": "https://app.example.com/api/webhooks/opengen",
  "webhookEvents": [
    "generation.completed",
    "generation.failed",
    "generation.delivery_ready"
  ]
}
JSON
)"

# Atomically claim the submission record (key + exact payload) before writing the CLI input file
(set -C; printf '%s\n' "$SUBMISSION_JSON" > webhook-job-submission.json)
jq '.payload' webhook-job-submission.json > webhook-job.json
chmod 600 webhook-job.json
opengen generate --input webhook-job.json --idempotency-key "$IDEMPOTENCY_KEY" > webhook-job-receipt.json
```

> [!NOTE]
> `webhookUrl` and `webhookEvents` are hashed into the `Idempotency-Key` request digest. Reusing the same key with a different webhook URL or event list returns `409 idempotency_conflict`.

## 2. Understand the five headers and signed message

Every webhook `POST` from OpenGen sends these exact five headers:

| Header                           | Format / Purpose                                                          |
| -------------------------------- | ------------------------------------------------------------------------- |
| `X-OpenGen-Webhook-Request-Id`   | Unique delivery UUID (deduplication key; matches JSON envelope `id`).     |
| `X-OpenGen-Webhook-Workspace-Id` | Owning workspace ID (matches JSON envelope `workspaceId`).                |
| `X-OpenGen-Webhook-Timestamp`    | Unix epoch timestamp in whole seconds (refreshed on every retry attempt). |
| `X-OpenGen-Webhook-Key-Id`       | Signing key `kid` published in `GET /.well-known/webhook-jwks.json`.      |
| `X-OpenGen-Webhook-Signature`    | 128-character lowercase hex Ed25519 signature (64 raw bytes).             |

The canonical UTF-8 message signed by Ed25519 is:

```text
{X-OpenGen-Webhook-Request-Id}\n{X-OpenGen-Webhook-Workspace-Id}\n{X-OpenGen-Webhook-Timestamp}\n{sha256Hex(rawBody)}
```

And the raw JSON envelope has this shape (prompts, credentials, and signed output URLs are intentionally omitted):

```json
{
  "id": "delivery-uuid",
  "jobId": "job-uuid",
  "workspaceId": "workspace-id",
  "event": "generation.delivery_ready",
  "createdAt": "2026-12-02T12:00:00.000Z",
  "data": {
    "jobId": "job-uuid",
    "status": "succeeded",
    "deliveryStatus": "available"
  }
}
```

## 3. Create `app/api/webhooks/opengen/route.ts`

Before deploying the handler, configure these required environment variables in your Next.js runtime:

- **`OPENGEN_WORKSPACE_ID`** (**required**): Your OpenGen workspace ID (from `GET /v1/balance` or the [Dashboard](/app)). OpenGen signing keys are gateway-wide and any workspace can configure a public `webhookUrl`, so signature verification alone proves the event came from the gateway — not that it belongs to your workspace. The handler below fails closed with `500` when `OPENGEN_WORKSPACE_ID` is unset and rejects foreign workspaces with `403`. (Multi-tenant apps should replace the single env check with a database lookup of authorized workspace IDs.)
- **`OPENGEN_API_KEY`** (**required**): A `read`-scoped (or higher) API key for fetching private outputs on `generation.delivery_ready`.
- **`OPENGEN_API_URL`** (optional): Defaults to `https://opengen.dev`.

Copy this complete Route Handler into your Next.js App Router project. Keep `export const runtime = 'nodejs'` so `node:crypto` Ed25519 verification works cleanly with zero third-party dependencies.

```ts
import { createHash, createPublicKey, verify, type KeyObject } from 'node:crypto';
import { NextResponse } from 'next/server';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

function stripTrailingSlash(url: string): string {
  let end = url.length;
  while (end > 0 && url.charCodeAt(end - 1) === 47) end -= 1;
  return url.slice(0, end);
}

const OPENGEN_ORIGIN = stripTrailingSlash(process.env.OPENGEN_API_URL ?? 'https://opengen.dev');
const JWKS_URL = `${OPENGEN_ORIGIN}/.well-known/webhook-jwks.json`;
const MAX_SKEW_SECONDS = 300;
const JWKS_CACHE_TTL_MS = 60 * 60 * 1000; // Matches Cache-Control: public, max-age=3600

interface WebhookPublicJwk {
  kty: 'OKP';
  crv: 'Ed25519';
  alg?: string;
  use?: string;
  kid: string;
  x: string;
}

interface WebhookEnvelope {
  id: string;
  jobId: string;
  workspaceId: string;
  event:
    | 'generation.started'
    | 'generation.completed'
    | 'generation.failed'
    | 'generation.cancelled'
    | 'generation.delivery_ready';
  createdAt: string;
  data: Record<string, unknown>;
}

let cachedJwks: { fetchedAt: number; keys: Map<string, KeyObject> } | null = null;

async function loadVerificationKey(kid: string): Promise<KeyObject | null> {
  const now = Date.now();
  const isFresh = cachedJwks !== null && now - cachedJwks.fetchedAt < JWKS_CACHE_TTL_MS;
  if (isFresh && cachedJwks!.keys.has(kid)) {
    return cachedJwks!.keys.get(kid)!;
  }

  // Force a refresh when cache is expired OR an unknown kid arrives during key rotation.
  const res = await fetch(JWKS_URL, {
    headers: { Accept: 'application/json' },
    cache: 'no-store',
  });
  if (!res.ok) {
    throw new Error(`Failed to fetch OpenGen webhook JWKS (${res.status})`);
  }
  const doc = (await res.json()) as { keys?: WebhookPublicJwk[] };
  const keys = new Map<string, KeyObject>();
  for (const jwk of doc.keys ?? []) {
    if (
      jwk.kty !== 'OKP' ||
      jwk.crv !== 'Ed25519' ||
      typeof jwk.kid !== 'string' ||
      typeof jwk.x !== 'string'
    ) {
      continue;
    }
    keys.set(
      jwk.kid,
      createPublicKey({
        key: { kty: 'OKP', crv: 'Ed25519', x: jwk.x },
        format: 'jwk',
      }),
    );
  }
  cachedJwks = { fetchedAt: now, keys };
  return keys.get(kid) ?? null;
}

// Replace with a durable database table in production (see Step 4 below).
const deliveryStates = new Map<string, 'pending' | 'completed'>();

async function claimDeliveryOnce(
  deliveryId: string,
): Promise<'claimed' | 'completed' | 'in_flight'> {
  const existing = deliveryStates.get(deliveryId);
  if (existing === 'completed') return 'completed';
  if (existing === 'pending') return 'in_flight';
  deliveryStates.set(deliveryId, 'pending');
  return 'claimed';
}

function completeDelivery(deliveryId: string): void {
  deliveryStates.set(deliveryId, 'completed');
}

function releaseDeliveryClaim(deliveryId: string): void {
  if (deliveryStates.get(deliveryId) === 'pending') {
    deliveryStates.delete(deliveryId);
  }
}

export async function POST(request: Request): Promise<NextResponse> {
  // 0. Fail closed unless expected workspace binding is configured.
  const expectedWorkspaceId = process.env.OPENGEN_WORKSPACE_ID?.trim();
  if (!expectedWorkspaceId) {
    return NextResponse.json({ error: 'webhook_workspace_unconfigured' }, { status: 500 });
  }

  // 1. Read exact raw UTF-8 body BEFORE parsing JSON.
  const rawBody = await request.text();

  // 2. Require all 5 OpenGen webhook headers.
  const requestId = request.headers.get('x-opengen-webhook-request-id')?.trim();
  const workspaceId = request.headers.get('x-opengen-webhook-workspace-id')?.trim();
  const timestamp = request.headers.get('x-opengen-webhook-timestamp')?.trim();
  const keyId = request.headers.get('x-opengen-webhook-key-id')?.trim();
  const signature = request.headers.get('x-opengen-webhook-signature')?.trim();

  if (!requestId || !workspaceId || !timestamp || !keyId || !signature) {
    return NextResponse.json({ error: 'missing_webhook_headers' }, { status: 401 });
  }

  // 3. Enforce numeric Unix timestamp within +/-300 seconds.
  if (!/^\d{1,15}$/.test(timestamp)) {
    return NextResponse.json({ error: 'invalid_timestamp' }, { status: 401 });
  }
  const nowSeconds = Math.floor(Date.now() / 1000);
  if (Math.abs(nowSeconds - Number(timestamp)) > MAX_SKEW_SECONDS) {
    return NextResponse.json({ error: 'timestamp_out_of_window' }, { status: 401 });
  }

  // 4. Require exact 128-character lowercase hex Ed25519 signature.
  if (!/^[0-9a-f]{128}$/.test(signature)) {
    return NextResponse.json({ error: 'invalid_signature_format' }, { status: 401 });
  }

  // 5. Look up public Ed25519 key by kid (refreshing JWKS on miss).
  let publicKey: KeyObject | null;
  try {
    publicKey = await loadVerificationKey(keyId);
  } catch {
    return NextResponse.json({ error: 'jwks_unavailable' }, { status: 503 });
  }
  if (!publicKey) {
    return NextResponse.json({ error: 'unknown_key_id' }, { status: 401 });
  }

  // 6. Verify Ed25519 signature over `${requestId}\n${workspaceId}\n${timestamp}\n${sha256Hex(rawBody)}`.
  const bodySha256 = createHash('sha256').update(rawBody, 'utf8').digest('hex');
  const signingMessage = Buffer.from(
    `${requestId}\n${workspaceId}\n${timestamp}\n${bodySha256}`,
    'utf8',
  );
  const sigBytes = Buffer.from(signature, 'hex');
  if (!verify(null, signingMessage, publicKey, sigBytes)) {
    return NextResponse.json({ error: 'invalid_signature' }, { status: 401 });
  }

  // 7. Parse JSON and confirm envelope headers match body fields.
  let envelope: WebhookEnvelope;
  try {
    envelope = JSON.parse(rawBody) as WebhookEnvelope;
  } catch {
    return NextResponse.json({ error: 'invalid_json' }, { status: 400 });
  }
  if (envelope.id !== requestId || envelope.workspaceId !== workspaceId) {
    return NextResponse.json({ error: 'envelope_header_mismatch' }, { status: 401 });
  }
  if (envelope.workspaceId !== expectedWorkspaceId) {
    return NextResponse.json({ error: 'unexpected_workspace' }, { status: 403 });
  }

  // 8. Deduplicate at-least-once deliveries by envelope.id while keeping failed attempts retryable.
  const claim = await claimDeliveryOnce(envelope.id);
  if (claim === 'completed') {
    return NextResponse.json({ ok: true, deduplicated: true });
  }
  if (claim === 'in_flight') {
    return NextResponse.json({ error: 'delivery_in_progress' }, { status: 409 });
  }

  // 9. Handle the event quickly (or durably enqueue before returning 2xx within 10 seconds).
  //    Roll back the claim and return a retryable 5xx if downstream processing fails.
  try {
    if (envelope.event === 'generation.delivery_ready') {
      const jobRes = await fetch(
        `${OPENGEN_ORIGIN}/v1/generations/${encodeURIComponent(envelope.jobId)}`,
        {
          headers: { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}` },
          cache: 'no-store',
        },
      );
      if (!jobRes.ok) {
        releaseDeliveryClaim(envelope.id);
        return NextResponse.json(
          { error: 'job_detail_unavailable', upstreamStatus: jobRes.status },
          { status: 503 },
        );
      }
      const job = await jobRes.json();
      // Persist job.status, job.settledMicros, and copy job.outputs to your app storage if needed.
      console.log('Ready outputs for job:', job.id, job.outputs?.length ?? 0);
    }
    completeDelivery(envelope.id);
    return NextResponse.json({ ok: true });
  } catch {
    releaseDeliveryClaim(envelope.id);
    return NextResponse.json({ error: 'webhook_processing_failed' }, { status: 500 });
  }
}
```

## 4. Deduplicate durably across serverless instances

An in-memory `Set` only works for single-process local testing—on Vercel or multi-replica deployments, retries will hit different instances. Persist `envelope.id` inside the same database transaction as your business side effect:

```sql
CREATE TABLE IF NOT EXISTS opengen_webhook_deliveries (
  delivery_id UUID PRIMARY KEY,
  job_id UUID NOT NULL,
  event TEXT NOT NULL,
  received_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Inside your handler transaction:
INSERT INTO opengen_webhook_deliveries (delivery_id, job_id, event)
VALUES ($1, $2, $3)
ON CONFLICT (delivery_id) DO NOTHING
RETURNING delivery_id;
```

If `RETURNING delivery_id` yields zero rows, commit immediately and return `200 OK` without repeating side effects.

## 5. Delivery, retry, and security semantics

- **At-least-once retries:** OpenGen keeps the exact same `id` and raw JSON body across retries, mints a fresh `X-OpenGen-Webhook-Timestamp` and `X-OpenGen-Webhook-Signature` on every attempt, and stops after **8 attempts** with delays of `30s`, `2m`, `10m`, `30m`, `2h`, `6h`, and `24h`.
- **Strict transport rules:** destinations must resolve exclusively to public IP addresses over HTTPS on port `443`. OpenGen re-validates DNS on every delivery attempt, pins the connection to the validated IP, follows **zero redirects** (`3xx` fails the attempt), times out after 10 seconds, and discards response bodies beyond `8 KiB`.
- **Key rotation:** operators rotate signing keys via `OPENGEN_WEBHOOK_SIGNING_KEYS_JSON` while keeping retired public keys in `/.well-known/webhook-jwks.json`. Refreshing the JWKS cache on an unknown `kid` handles rotation with zero downtime.

## Next steps

- Review full webhook concepts and Python verification examples in [Webhooks](/docs/webhooks).
- Running your own OpenGen gateway and configuring `OPENGEN_WEBHOOK_SIGNING_KEYS_JSON`? Continue to [Self-Hosting OpenGen](/docs/guides/self-hosting).
