# Webhooks

Tell another system when your content changes, with signed payloads and retries you can inspect.

A webhook is an HTTP call Nextly makes when something happens to your content — a post is
published, a page is deleted — so another system can react without polling.

## Availability

|            |                                                                                                     |
| ---------- | --------------------------------------------------------------------------------------------------- |
| Built in   | No plugin required                                                                                  |
| Admin      | A **Webhooks** section for endpoints, secrets and delivery history                                  |
| Permission | Managing endpoints is governed by `create-webhooks`, `update-webhooks` and `delete-webhooks` grants |

## Endpoints

An endpoint is a URL plus a filter describing which events it wants. Registering everything
to one URL works, but filtering per endpoint means a receiver is not woken for events it
will ignore.

## Event types

An endpoint subscribes to event types by their exact ids, or to `*` for every current and future
one. Core's are `entry.created`, `entry.updated`, `entry.deleted`, `entry.published`,
`entry.unpublished`, `entry.status_changed`, `single.updated`, `single.published`,
`single.unpublished`, `media.uploaded`, `media.updated`, `media.deleted`, `user.created`,
`user.deleted` and the form builder's `form.submission.created`. `*` is the only wildcard. `GET /admin/api/webhooks/event-types` lists every type an endpoint may
subscribe to, with the plugin or `core` that declares it, to anyone who may read, create or update
webhooks.

A plugin declares its own types in `contributes.webhookEvents`, each in its namespace (its admin slug
and a dot):

```ts
contributes: {
  webhookEvents: [{ type: "acme-shop.order.paid", label: "Order paid" }],
}
```

Startup refuses a type outside that namespace, one of core's, one declared twice, or one that isn't
lower-case segments separated by dots. These are webhook types, sent to other systems; they are
separate from `contributes.events`, the plugin's own events inside the server.

An endpoint can subscribe to a declared type, and the admin's webhook form offers it. When a plugin is
disabled its types are no longer offered and a new subscription to one is refused, while an endpoint
that already subscribes keeps it, shown in the admin as unavailable.

The plugin records an event of one of its types with `ctx.webhooks.record`. Inside its own
`ctx.db.transaction`, pass the transaction's handle as `tx`: the event commits with the plugin's
writes and is never delivered if they roll back. Without `tx` it is recorded on its own, and a call
made while a transaction is open is refused.

```ts
await ctx.db.transaction(async tx => {
  // … the plugin's own writes, through tx …
  await ctx.webhooks.record({
    type: "acme-shop.order.paid",
    id: order.id,
    data: { total: order.total },
    tx,
  });
});
```

A type the plugin doesn't declare, another plugin's or one of core's, is refused by name before
anything is written. The event goes to the endpoints subscribed to its type or to `*`, and to no
other. Its resource is `{ "kind": "plugin", "plugin": "acme-shop", "id": "…" }`, with the plugin's
admin slug and no `collection`, so an endpoint limited to certain collections never receives it, even
one limited to a collection with the same slug as the plugin. The delivery log shows it as
`plugin acme-shop · <id>`. `previous` is optional, and the event's changed fields are worked out from
it as core's are. Like core's events, nothing is recorded while no endpoint exists and the audit trail
is off. This surface is experimental.

## Signing

Every delivery is signed so the receiver can prove it came from you and was not modified.

Nextly follows [Standard Webhooks](https://www.standardwebhooks.com/). A secret is shown to
you as `whsec_` followed by base64 key material, and **the key is the decoded bytes, not the
string you were shown**:

```
key           = base64_decode(secret without its "whsec_" prefix)
signedContent = "<id>.<timestamp>.<rawBody>"
signature     = base64(HMAC_SHA256(key, signedContent))
```

The `webhook-signature` header carries versioned tokens shaped `v1,<signature>`. During a
secret rotation a delivery is signed with **every** active secret, and the tokens are joined
by **spaces**:

```
webhook-signature: v1,<sigA> v1,<sigB>
```

So verification is: **check the timestamp is recent, then** split the header on whitespace,
split each token on its comma, and accept if any token matches.

The freshness check is not optional. Signing the timestamp proves it was not altered; it does
not make the delivery expire. Nextly's own verifier (what a plugin calls as
`ctx.security.webhooks.verify` with `standardWebhooks`) rejects anything outside a
**300-second (5 minute)** tolerance *before* it compares signatures, and a receiver that skips
that step will accept a captured request forever.

> [!WARNING]
> Three ways to reject every authentic delivery, in the order people hit them: using the
> `whsec_...` string as the HMAC key instead of its decoded bytes; comparing against the whole
> header without stripping `v1,`; and splitting only on commas, which folds the next token into
> the first signature and breaks the moment you rotate a secret.
>
> And one way to accept an inauthentic one: matching the HMAC but never checking the timestamp,
> which leaves you replayable indefinitely.
>
> A Standard Webhooks verifier library does all four correctly. Prefer one over hand-rolling
> this.

Three headers travel with each delivery:

| Header              | Holds                                               |
| ------------------- | --------------------------------------------------- |
| `webhook-id`        | The delivery's id, and part of the signed content   |
| `webhook-timestamp` | When it was signed, also part of the signed content |
| `webhook-signature` | The signature itself                                |

Because the timestamp is signed, a captured payload cannot be replayed later under its
original signature.

Verify against the **raw body**, before any JSON parsing. Re-serializing first changes the
bytes and the signature will not match — the usual reason a correct implementation appears
to fail.

## Delivery, retries and the outbox

An event is written to a durable **outbox** in the same transaction as the content change,
and delivered from there. So a webhook cannot be lost because the process died between
saving a document and making the HTTP call, and it cannot fire for a change that was
rolled back.

Delivery is then retried on a schedule:

|               |              |
| ------------- | ------------ |
| Attempts      | 6 by default |
| First retry   | 30 seconds   |
| Longest delay | 1 hour       |

A `2xx` response counts as delivered. A `429` or any `5xx` is retried. Other `4xx`
responses are not retried, because a receiver rejecting the request as malformed will
reject it again.

## Delivery history

Deliveries are recorded so you can see what was sent, what came back and how many attempts
it took. That history is trimmed on a schedule — see
[retention](https://nextlyhq.com/docs/webhooks/retention.md).

## Related

* [Retention](https://nextlyhq.com/docs/webhooks/retention.md) — how long delivery history is kept
* [Background jobs](https://nextlyhq.com/docs/jobs.md) — work that runs outside the request
* [ISR caching](https://nextlyhq.com/docs/guides/isr-caching.md) — updating your own pages on a change
