# Receiving webhooks (/guides/receiving-webhooks)

This guide walks through building an endpoint that receives deliveries from
Use Webhooks, from the first request to running it in production. It covers
what a delivery looks like, how to verify that it really came from us, how to
respond, and how to stay correct when the same event arrives more than once.

<Callout title="Demo page">
This page exercises every element the docs support: headings, lists, tables,
code fences, code tabs and callouts. Use it to check styling changes.
</Callout>

## What a delivery looks like [#what-a-delivery-looks-like]

Every delivery is an HTTP `POST` to your destination's URL with a JSON body and
three signing headers. The headers follow the
[Standard Webhooks](https://www.standardwebhooks.com) specification, so any of
its libraries can verify them.

### Headers [#headers]

| Header              | Example                       | Meaning                                              |
| ------------------- | ----------------------------- | ---------------------------------------------------- |
| `webhook-id`        | `dlv_01JC3…`                  | The delivery's id. Stable across retries.            |
| `webhook-timestamp` | `1763200000`                  | Unix seconds when this attempt was signed.           |
| `webhook-signature` | `v1,K5oZfzN95Z9UVu1EsfQmfVNQ…` | One or more space-separated `v1,<base64>` signatures. |
| `content-type`      | `application/json`            | Always JSON.                                         |
| `user-agent`        | `use-webhooks/1.0`            | Identifies the sender.                               |

Any custom headers you configured on the destination are sent too. They can't
override the headers above.

### Body [#body]

The body wraps the payload you published with its event type and the time the
event was created:

```json
{
  "type": "invoice.paid",
  "timestamp": "2026-11-15T09:12:44.512Z",
  "data": {
    "invoiceId": "inv_8812",
    "amount": 4200,
    "currency": "usd"
  }
}
```

`data` is exactly what you sent to `POST /v1/publish`, untouched.

## Verifying signatures [#verifying-signatures]

Anyone who learns your endpoint's URL can send it requests. The signature is how
you tell ours apart: it's an HMAC-SHA256 of the delivery, keyed with your
destination's signing secret, which only you and Use Webhooks know.

<Callout type="warning" title="Verify the raw body">
Compute the signature over the exact bytes you received. Parsing the JSON and
re-serializing it can reorder keys or change whitespace, and the signature
will no longer match.
</Callout>

### How the signature is built [#how-the-signature-is-built]

1. Take the `webhook-id`, the `webhook-timestamp` and the raw body.
2. Join them with dots: `{id}.{timestamp}.{body}`.
3. Strip the `whsec_` prefix from your secret and base64-decode the rest to get the key.
4. HMAC-SHA256 the joined string with that key, then base64-encode the result.
5. Prefix it with `v1,`.

The header can hold several signatures separated by spaces. Accept the request
if **any** of them matches yours. This is what keeps verification working during
a secret rotation (see [Rotating secrets](#rotating-secrets)).

### With a library [#with-a-library]

The quickest route is the official Standard Webhooks library for your language.
Pass it the raw body and the headers, and it checks the signature and the
timestamp for you.

<CodeTabs>
```ts
import { Webhook } from "standardwebhooks";

const wh = new Webhook(process.env.USE_WEBHOOKS_SECRET!);

export async function POST(request: Request) {
  const body = await request.text();
  const headers = Object.fromEntries(request.headers);

  let event: { type: string; data: unknown };
  try {
    event = wh.verify(body, headers) as typeof event;
  } catch {
    return new Response("invalid signature", { status: 400 });
  }

  await queue.add(event.type, event.data);
  return new Response(null, { status: 204 });
}
```

```shell
# Send yourself a signed test delivery from the CLI
curl -X POST https://api.usewebhooks.dev/v1/publish \
  -H "X-API-Key: sk_prod_…" \
  -d '{"eventType":"invoice.paid","payload":{"invoiceId":"inv_8812","amount":4200}}'
```
</CodeTabs>

### By hand [#by-hand]

If there's no library for your stack, the check is a few lines. Compare
signatures with a constant-time function so the comparison itself doesn't leak
how many characters matched.

```ts
import { createHmac, timingSafeEqual } from "node:crypto";

const TOLERANCE_SECONDS = 5 * 60;

export function verify(secret: string, headers: Headers, body: string): boolean {
  const id = headers.get("webhook-id");
  const timestamp = headers.get("webhook-timestamp");
  const signatures = headers.get("webhook-signature");
  if (!id || !timestamp || !signatures) return false;

  // Reject old or future-dated attempts to block replays.
  const age = Math.abs(Date.now() / 1000 - Number(timestamp));
  if (!Number.isFinite(age) || age > TOLERANCE_SECONDS) return false;

  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = createHmac("sha256", key)
    .update(`${id}.${timestamp}.${body}`)
    .digest("base64");

  return signatures.split(" ").some((entry) => {
    const [version, signature] = entry.split(",");
    if (version !== "v1" || !signature) return false;
    const a = Buffer.from(signature);
    const b = Buffer.from(expected);
    return a.length === b.length && timingSafeEqual(a, b);
  });
}
```

### Rejecting replays [#rejecting-replays]

The timestamp is part of what's signed, so an attacker can't change it without
breaking the signature. Rejecting attempts older than a few minutes means a
captured request can't be replayed later. Five minutes is a sensible window;
keep your server's clock synced with NTP so honest requests aren't rejected.

## Responding [#responding]

Your response tells us whether the delivery worked.

- **Any `2xx`** marks the attempt as succeeded. The body is ignored.
- **Any other status, or no response before the timeout**, marks it as failed
  and schedules a retry.
- **`410 Gone`** marks it as failed permanently: no more retries for this
  delivery. Use it when the thing the event refers to no longer exists on your side.

<Callout type="success" title="Answer first, work later">
Put the event on your own queue and return `204` straight away. Doing the real
work inside the request makes slow days look like failures, and those turn
into retries that add even more load.
</Callout>

### Timeouts [#timeouts]

Each destination has its own timeout, set when you create it. An attempt that
hasn't received response headers by then is cut off and counted as failed, even
if your handler finishes the work afterwards. That's one more reason to
acknowledge quickly and process in the background.

## Retries [#retries]

Failed attempts are retried on a schedule set per destination (falling back to
your organization's default).

| Setting               | Values                    | What it controls                                  |
| --------------------- | ------------------------- | ------------------------------------------------- |
| `retryStrategy`       | `exponential` or `linear` | How the gap between attempts grows.               |
| `baseIntervalSeconds` | seconds                   | The first gap, which the strategy grows from.     |
| `maxAttempts`         | `1` – `50`                | Total attempts, including the first, before giving up. |

With an exponential strategy each gap is roughly double the last, which gives a
struggling server room to recover. A linear strategy waits the same amount each
time, which suits endpoints that fail briefly and come back quickly.

Every attempt shows up under **Deliveries** in the dashboard with its status
code, duration and response body, and any failed delivery can be retried by
hand once you've fixed the problem.

## Handling duplicates [#handling-duplicates]

Retries mean the same delivery can reach you more than once: your server might
finish the work, then time out before the `2xx` makes it back. Design your
handler so that processing a delivery twice has the same effect as processing it
once.

The `webhook-id` header is the key to this. It stays the same across every retry
of a delivery, so you can record the ids you've handled and skip repeats:

```ts
export async function handle(id: string, event: { type: string; data: unknown }) {
  // A unique constraint on delivery_id makes the insert the lock.
  const inserted = await db
    .insertInto("processed_deliveries")
    .values({ delivery_id: id })
    .onConflict((oc) => oc.doNothing())
    .executeTakeFirst();

  if (inserted.numInsertedOrUpdatedRows === 0n) return; // already handled

  await process(event);
}
```

<Callout type="info" title="Keep the table small">
You only need to remember ids for as long as retries can arrive. Deleting rows
older than a few days keeps the table from growing forever.
</Callout>

### Ordering [#ordering]

Deliveries are not guaranteed to arrive in the order events were published. A
retry of an older event can land after a newer one. If order matters, compare
the body's `timestamp` with what you've already stored and ignore anything older.

## Rotating secrets [#rotating-secrets]

Rotate a destination's signing secret whenever it may have leaked, or on a
regular schedule. Rotation is built so you never drop a delivery:

1. Rotate the secret in the dashboard or through the API. You get the new secret,
   and the previous one keeps working until `previousSecretExpiresAt`.
2. While both are valid, every delivery is signed with **both** secrets, so the
   `webhook-signature` header carries two signatures.
3. Deploy the new secret to your endpoint. Because you accept any matching
   signature, requests verify before and after the deploy.
4. Once the previous secret expires, deliveries carry only the new signature.

<Callout type="error" title="If a secret leaks">
Rotate straight away and choose the shortest expiry for the old secret. Until it
expires, whoever holds it can still sign requests your endpoint will accept.
</Callout>

## Testing locally [#testing-locally]

Your endpoint has to be reachable from the internet to receive deliveries. While
developing, expose your local server with a tunnel and point a destination at it:

```shell
# Start your app, then open a tunnel to it
npx localtunnel --port 3000
```

Then publish a test event and watch it arrive in your terminal and in the
dashboard's **Deliveries** page.

## Production checklist [#production-checklist]

Before you go live, check each of these:

- [ ] The endpoint is served over HTTPS.
- [ ] Every request's signature is verified against the raw body.
- [ ] Attempts older than five minutes are rejected.
- [ ] The handler returns `2xx` within the destination's timeout.
- [ ] Work happens on a queue, not inside the request.
- [ ] Repeated `webhook-id`s are detected and skipped.
- [ ] The signing secret lives in your secret manager, not in source control.
- [ ] You know how to rotate the secret without downtime.

## Troubleshooting [#troubleshooting]

### Every signature fails [#every-signature-fails]

- Make sure you're hashing the **raw** body. Frameworks that parse JSON for you
  often need a raw-body option on this one route.
- Check you're using this destination's secret. Each destination has its own.
- Make sure the `whsec_` prefix is stripped before decoding the key.

### Deliveries show as timed out, but my handler ran [#deliveries-show-as-timed-out-but-my-handler-ran]

Your handler is doing its work before responding. Return `2xx` first and move
the work to a background job.

### I'm receiving the same event twice [#im-receiving-the-same-event-twice]

That's a retry after an attempt we couldn't confirm. Deduplicate on `webhook-id`
as described in [Handling duplicates](#handling-duplicates).

> Still stuck? Open the failing delivery in the dashboard: the response body and
> status code your server returned are usually enough to spot the cause.