# Webhooks

> Settings → Webhooks, done properly: "Send test" runs a bead down the wire to the endpoint and back in the answer's colour, and every delivery opens into its request and response.

Webhook settings are usually a table of URLs and a "Send test" button that answers with a toast somewhere else. Here every endpoint opens in place. The test is drawn as the request it is: a bead leaves your app and runs the hairline to the endpoint, the endpoint's chip pulses while it answers, and the bead comes home in the answer's colour as "200 OK in 182 ms" rolls in; the delivery lands on top of the list below. Every delivery opens into its request and response, the tab highlight sliding between them, and Redeliver sends it again: the new attempt arrives on top. The signing secret stays dots until you reveal it. Enabled is a switch that saves itself, and Delete stretches the bin into a confirm and folds the endpoint away. A new endpoint fades in on top, already open on Send test.

## Install

```bash
npx shadcn@latest add @hairline/webhooks
```

Needs React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

- npm: `lucide-react`
- Hairline UI components it needs (the CLI installs them too): `text-morph`, `number-roll`, `status-button`
- Docs and live preview: https://hairlineui.com/ui/webhooks
- Registry item (source): https://hairlineui.com/r/webhooks.json

## Usage

```tsx
import { Webhooks } from "@/components/webhooks";

<Webhooks
  defaultValue={endpoints}
  events={[{ value: "invoice.paid" }, { value: "customer.created" }]}
  onCreate={(input) => api.createEndpoint(input)}
  onTest={(endpoint, event) => api.sendTest(endpoint.id, event)}   // → the delivery
  loadDeliveries={(endpoint, before) => api.deliveries(endpoint.id, before?.id)}
/>
```

## Signed deliveries from your own route

The test route signs the body with the endpoint's secret, posts it with a 10 second timeout, times the answer and stores the delivery, which is exactly what the card shows. Real events go through the same function from your queue. With Svix or Hookdeck, these routes call their APIs instead and map the attempts to the same shape.

```tsx
// lib/deliver.ts
import { createHmac, randomUUID } from "node:crypto";
import { db } from "@/lib/db";

export async function deliver(endpoint: { id: string; url: string; secret: string }, event: string, data: unknown) {
  const body = JSON.stringify({ id: `evt_${randomUUID()}`, type: event, created: Math.floor(Date.now() / 1000), data });
  const timestamp = Math.floor(Date.now() / 1000);
  const signature = createHmac("sha256", endpoint.secret).update(`${timestamp}.${body}`).digest("hex");
  const started = performance.now();
  let status: number | null = null;
  let response = "";
  try {
    const res = await fetch(endpoint.url, {
      method: "POST",
      body,
      headers: { "Content-Type": "application/json", "Webhook-Timestamp": String(timestamp), "Webhook-Signature": signature },
      signal: AbortSignal.timeout(10_000),
    });
    status = res.status;
    response = (await res.text()).slice(0, 8000);
  } catch {
    // No answer: status stays null.
  }
  return db.delivery.create({
    data: { endpointId: endpoint.id, event, status, durationMs: Math.round(performance.now() - started), request: body, response },
  });
}

// app/api/webhooks/[id]/test/route.ts
export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const endpoint = await db.endpoint.findUniqueOrThrow({ where: { id: (await params).id } });
  const { event } = await req.json();
  return Response.json(await deliver(endpoint, event, sampleFor(event)));
}

// app/settings/webhooks.tsx
"use client";
<Webhooks
  defaultValue={endpoints}
  events={eventTypes}
  appName="Relay"
  onCreate={async (input) => (await fetch("/api/webhooks", { method: "POST", body: JSON.stringify(input) })).json()}
  onTest={async (ep, event) => (await fetch(`/api/webhooks/${ep.id}/test`, { method: "POST", body: JSON.stringify({ event }) })).json()}
  loadDeliveries={async (ep, before) => (await fetch(`/api/webhooks/${ep.id}/deliveries?before=${before?.id ?? ""}`)).json()}
  onRedeliver={async (d, ep) => (await fetch(`/api/webhooks/${ep.id}/deliveries/${d.id}/retry`, { method: "POST" })).json()}
  onRevealSecret={async (ep) => (await (await fetch(`/api/webhooks/${ep.id}/secret`)).json()).secret}
/>
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `events` | `{ value, description? }[]` | – | Event types an endpoint can subscribe to. |
| `onCreate` | `({ url, events }) => Promise<WebhookEndpoint>` | – | Creates an endpoint: { id, url, events, enabled?, lastDelivery? }. Throw to keep the form and show the message. |
| `onTest` | `(endpoint, event) => Promise<WebhookDelivery>` | – | Sends a test and returns the delivery: { id, event, status (null for no answer), durationMs?, at, attempt?, request?, response? }. |
| `loadDeliveries` | `(endpoint, before?) => Promise<WebhookDelivery[]>` | – | Recent deliveries, newest first, loaded the first time an endpoint opens; before is the oldest one shown when paging back. Return an empty list when there are no more. |
| `onRedeliver` | `(delivery, endpoint) => Promise<WebhookDelivery>` | – | Sends a delivery again and returns the new attempt. Without it there is no Redeliver. |
| `onRevealSecret` | `(endpoint) => Promise<string>` | – | Fetches the signing secret when someone asks to see it. Without it the secret stays dots. |
| `onToggle` | `(endpoint, enabled) => Promise<unknown>` | – | Turns an endpoint on or off; the switch moves at once and goes back if this throws. |
| `onDelete` | `(endpoint) => Promise<unknown>` | – | Deletes an endpoint after a confirm. |
| `value` | `WebhookEndpoint[]` | – | Controlled endpoints. lastDelivery updates after every test and redelivery. |
| `defaultValue` | `WebhookEndpoint[]` | – | Starting endpoints when uncontrolled. |
| `onValueChange` | `(endpoints) => void` | – | Every add, toggle, delete and new delivery. |
| `appName` | `string` | `"Your app"` | The near end of the test's wire. |

## States

- **add**: "Add endpoint" opens the form by height: the URL (https://, or http://localhost) and event chips whose checks draw in. A bad URL shakes the field and says why. The new endpoint fades down 6px out of a blur on top of the list, open, with focus on Send test.
- **open**: A row opens by height in 460ms; its chevron turns. The first time, recent deliveries load (loadDeliveries) with a spinner, then fade in.
- **test**: The bead fades in and runs the wire to the endpoint in 620ms; the endpoint's chip pulses a ring every 900ms until onTest resolves; the bead comes back in emerald (2xx), amber (3xx/4xx) or red (5xx, no answer) in 640ms. Then the status code and the milliseconds roll in, the button says Delivered or shakes and says Send again, and the delivery glides in on top of the list.
- **delivery**: Each row shows the status code in its colour, the event, how long ago and how long the endpoint took. It opens by height into Request and Response (pretty-printed JSON); the tab highlight slides 360ms between them.
- **redeliver**: Redeliver → Sending → Sent with a drawn check; the new attempt ("attempt 2") fades in on top while the rest glide down, and the endpoint's last status updates.
- **secret**: Dots until Reveal (which says Revealing while onRevealSecret runs); then the secret fades in from a blur with a copy button whose icon draws a check, and Hide.
- **enable / delete**: The switch's thumb is thrown with a slight overshoot and its label says Saving until onToggle resolves (or is thrown back if it throws). Delete endpoint stretches out of the bin; a check draws, then the endpoint folds away.

## What it handles

Webhook settings are usually a table of URLs and a “Send test” button that answers with a toast somewhere else. This shows the test as the request it is, and keeps every delivery inspectable.

- **Add endpoints with events**: A URL and event chips. A bad URL shakes the field and says why.
- **Send test, visibly**: A bead runs the wire to the endpoint, the chip pulses while it answers, and the bead returns in the answer’s colour with “200 OK in 182 ms”.
- **Every delivery is inspectable**: Each shows its status, event, time and duration, and opens into the request and the response as JSON.
- **Redeliver**: Send a delivery again and the new attempt arrives on top of the list.
- **The secret stays hidden**: The signing secret is dots until someone asks to reveal it, with a copy button once shown.
- **Enable and delete safely**: The enabled switch saves itself and goes back if it fails. Delete asks first.

## Replaces

an endpoints table, a Send test button, a deliveries log, a request and response viewer, a Redeliver button, a secret reveal, an enable switch

## Where it fits

- **Developer dashboards**: The Settings → Webhooks page of a product that sends events.
- **Payments and billing platforms**: Let customers choose which events go to which URL.
- **Integration platforms**: Show where events are sent and whether they arrived.
- **Delivery debugging**: Inspect the request and response of a failed delivery.

## Notes

- Each endpoint is a button with aria-expanded; its details are its own region. Deliveries are a list whose rows open with aria-expanded, and Request / Response is a tablist that arrows move between.
- The test result ("200 OK in 182 ms") is a status message; adding, deleting, toggling and redelivering are announced too. The wire itself is for the eye only.
- Status codes are told by number and word, not colour alone: 2xx emerald, 3xx and 4xx amber, 5xx and no answer red.
- The bead and the pulse are Web Animations that only run while a test is in flight; deliveries glide with additive transforms (use-row-motion).
- Reduced motion skips the bead, the pulse, the fades and the glides; results and rows still change in place.

License: MIT (https://hairlineui.com/license#components)
