> ## Documentation Index
> Fetch the complete documentation index at: https://usefoil.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Webhooks

> Receive signed webhook events from Foil when sessions change state, verify HMAC signatures, and handle retries idempotently.

Foil posts signed JSON events to your server when interesting things happen on a session. Use webhooks to react asynchronously: persist a verdict to your warehouse or fan out to a workflow.

## Event types

An endpoint receives the events it subscribes to.

| Event | Sent when |
| - | - |
| `session.result.persisted` | A non-provisional verdict has been written for a session. Fires once per session, the first time Foil persists a final result - provisional updates do not deliver. |

Foil also sends `webhook.test` events when you send a test event to an endpoint. You can't subscribe to `webhook.test`.

## Envelope

Every event is wrapped in the same envelope:

```json theme={"dark"}
{
  "id": "wevt_0123456789abcdef0123456789abcdef",
  "object": "webhook_event",
  "type": "session.result.persisted",
  "created": "2026-03-24T20:00:05.000Z",
  "data": { ... }
}
```

| Field | Description |
| - | - |
| `id` | Unique event identifier. Use it to dedupe retries - see [Idempotency](#idempotency). |
| `object` | Always `"webhook_event"`. |
| `type` | The event type. Switch on this to dispatch to the right handler. |
| `created` | ISO-8601 UTC timestamp of when the event was recorded. |
| `data` | Event-specific payload. See [Event payloads](#event-payloads). |

## Event payloads

### `session.result.persisted`

The `data` object describes the decision that Foil persisted for the session:

```json theme={"dark"}
{
  "object": "session_result",
  "session": { "id": "sid_0123456789abcdefghjkmnpqrs" },
  "event": {
    "id": "evt_23456789abcdefghjkmnpqrstv",
    "scoring_event_id": "1842",
    "phase": "behavioral",
    "is_provisional": false,
    "persisted_at": "2026-03-24T20:00:05.000Z"
  },
  "decision": {
    "verdict": "bot",
    "risk_score": 94,
    "score": 0.94,
    "manipulation": { "score": 18, "verdict": "low" }
  },
  "visitor_fingerprint": { "id": "vid_456789abcdefghjkmnpqrstvwx" },
  "device_cluster": null,
  "request": {
    "url": "https://example.com/signup",
    "user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.6312.86 Safari/537.36",
    "ip_address": "203.0.113.9",
    "screen_size": "1440x900",
    "is_touch_capable": false,
    "platform": "macOS",
    "first_seen": "2026-03-24T19:59:58.000Z",
    "risk_time": "2026-03-24T20:00:05.000Z"
  },
  "score_breakdown": {
    "categories": { "environment": 60, "fingerprint": 30, "keyboard": 10 }
  },
  "signals": [
    { "id": "...", "category": "environment", "confidence": "exact", "score": 60, "role": "risk" }
  ],
  "attribution": {
    "bot": {
      "labels": [{ "kind": "actor", "value": "automation", "label": "Automation", "confidence": 97 }],
      "behaviors": []
    }
  }
}
```

| Field | Description |
| - | - |
| `object` | Always `session_result`. |
| `session.id` | The session ID. Pass it to [`GET /v1/sessions/:sessionId`](https://usefoil.com/docs/api-reference/sessions) for the full investigation detail. |
| `event` | The decision that triggered the webhook. `id` is the event ID, `scoring_event_id` is Foil's internal identifier for the scoring record, `phase` is `snapshot`, `behavioral`, or `null`, and `persisted_at` is when Foil stored the result. `is_provisional` is always `false` for this event type. |
| `decision.verdict` | `bot`, `human`, or `inconclusive`. |
| `decision.risk_score` | The risk score as an integer from `0` to `100`. |
| `decision.score` | The same risk score as a number from `0` to `1`. Every other score and confidence in this payload is an integer from `0` to `100`, the same scale the Sessions API uses. |
| `decision.manipulation` | An object with a manipulation `score` from `0` to `100` and a `verdict` of `none`, `low`, `medium`, or `high`, or `null` when Foil has no manipulation assessment. The `score` can be `null` when only a verdict is available. |
| `visitor_fingerprint` | An object with the visitor fingerprint `id`, or `null` when Foil didn't identify a visitor. |
| `device_cluster` | `null`, or an object with `object` set to `device_cluster`, the cluster `id`, a `confidence` from `0` to `100`, and `matched_by`, which is `visitor_membership`, `fingerprint`, or `new`. It is `null` unless device-cluster results are enabled for your organization. |
| `request` | The request context. `url`, `user_agent`, `ip_address`, `screen_size`, `platform`, `first_seen`, and `risk_time` can be `null`. `first_seen` is when Foil first received a request for the session and `risk_time` is when it received the request that produced this result, both as ISO-8601 UTC timestamps. `is_touch_capable` is a boolean. |
| `score_breakdown.categories` | An object that maps each scoring category to its score from `0` to `100`. |
| `signals` | The risk signals that fired for the decision. Each item has an opaque `id`, a `category`, a `confidence`, a `score` from `0` to `100`, and a `role`, which is always `risk`. The list is empty unless raw signal access is enabled for your organization. The IDs are identifiers, not descriptions. For plain-language findings, read `highlights` from the session detail endpoint. |
| `attribution.bot` | `null`, or an object with `labels` (each with `kind`, `value`, `label`, and `confidence`) and `behaviors` (each with `channel`, `value`, `label`, and `confidence`). Confidences are integers from `0` to `100`. The object matches `attribution` in [session detail](https://usefoil.com/docs/api-reference/sessions.md). [Attribution labels](https://usefoil.com/docs/attribution.md) lists every value. |

### `webhook.test`

A test event carries this `data`:

```json theme={"dark"}
{
  "object": "webhook_test",
  "endpoint": { "id": "we_0123456789abcdef0123456789abcdef" },
  "message": "This is a Foil webhook test event."
}
```

`endpoint.id` is the endpoint that received the test.

## Endpoints

A **webhook endpoint** is a URL on your server, an event-type subscription list, and a signing secret. Each endpoint is scoped to a single organization. You can have multiple endpoints - for example, separate URLs for staging and production, or per-team fan-out.

### Endpoint API

All webhook and event endpoints require a live secret key (`sk_live_*`) with a webhook scope, and they work only for the organization that owns the key. A test key gets `403` with `auth.live_key_required`, because endpoints receive live events and the events list returns live payloads. See [Authentication](https://usefoil.com/docs/api-reference/authentication.md#scopes).

| Method | Path | Purpose | Required scope |
| - | - | - | - |
| `GET` | `/v1/organizations/{organizationId}/webhooks/endpoints` | List all endpoints, newest first. This endpoint takes no query parameters. | `webhooks:read` |
| `POST` | `/v1/organizations/{organizationId}/webhooks/endpoints` | Create an endpoint. Returns `201` with the `signing_secret`. | `webhooks:manage` |
| `PATCH` | `/v1/organizations/{organizationId}/webhooks/endpoints/{endpointId}` | Update the `name`, `url`, `event_types`, or `status`. | `webhooks:manage` |
| `DELETE` | `/v1/organizations/{organizationId}/webhooks/endpoints/{endpointId}` | Disable an endpoint. Returns `200` with the endpoint. | `webhooks:manage` |
| `POST` | `/v1/organizations/{organizationId}/webhooks/endpoints/{endpointId}/rotations` | Rotate the signing secret. Returns `201` with the new `signing_secret`. | `webhooks:manage` |
| `POST` | `/v1/organizations/{organizationId}/webhooks/endpoints/{endpointId}/test` | Send a test event. Returns `202`. | `webhooks:manage` |
| `GET` | `/v1/organizations/{organizationId}/events` | List events with their deliveries. | `webhooks:read` |
| `GET` | `/v1/organizations/{organizationId}/events/{eventId}` | Retrieve one event. | `webhooks:read` |

An unknown endpoint or event ID returns `404`, and an invalid `name`, `url`, or `event_types` value returns `422`.

### Create an endpoint

From the [dashboard](https://dashboard.usefoil.com), open **Webhooks**. In the **Endpoints** card, click **New endpoint**, name it, paste your HTTPS URL, and check the events you want to receive. The dashboard asks you to verify your identity before it creates, edits, or rotates an endpoint. Copy the `signing_secret` from the success screen - **it is shown once.** Store it as `FOIL_WEBHOOK_SECRET` (or similar) on the receiving service.

To create an endpoint via the API, `POST /v1/organizations/{organizationId}/webhooks/endpoints` with an `sk_live_*` key that has the `webhooks:manage` scope:

```bash theme={"dark"}
curl https://api.usefoil.com/v1/organizations/org_.../webhooks/endpoints \
  -X POST \
  -H "Authorization: Bearer sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Production receiver",
    "url": "https://app.example.com/webhooks/foil",
    "event_types": ["session.result.persisted"]
  }'
```

The 201 response includes the `signing_secret` exactly once. Persist it before discarding the response.

### URL requirements

Foil validates every endpoint URL on create, on update, and again before each delivery attempt:

* **HTTPS only** in production. Plain HTTP is allowed only against `localhost` / `127.0.0.1` in non-production environments.
* **No credentials in the URL** - `https://user:pass@host/path` is rejected.
* **Public IPs only.** Foil resolves the hostname and refuses to deliver to private, reserved, or link-local ranges. This protects your infrastructure from SSRF-style misuse if a webhook secret leaks.
* **Reachable.** DNS must resolve and the request must complete within the per-attempt timeout (10 seconds).

If your receiver sits behind a private network, terminate TLS on a public ingress and proxy internally.

### Event subscriptions

A subscription is the `(endpoint, event_type)` pair. When you `PATCH .../endpoints/{endpointId}` with a new `event_types` array, Foil **replaces** the endpoint's subscriptions - pass the full desired set, not just additions. Foil ignores event types it doesn't support, and an array with no supported event type returns `422`.

```bash theme={"dark"}
curl https://api.usefoil.com/v1/organizations/org_.../webhooks/endpoints/we_... \
  -X PATCH \
  -H "Authorization: Bearer sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{ "event_types": ["session.result.persisted"] }'
```

### Disable, re-enable, or delete

* **Disable** - `PATCH .../endpoints/{endpointId}` with `{"status": "disabled"}`, or **Disable endpoint** in the endpoint's menu in the dashboard. New events are not queued for the endpoint; in-flight deliveries finish in `skipped` state.
* **Re-enable** - `PATCH .../endpoints/{endpointId}` with `{"status": "active"}`, or **Enable endpoint** in the dashboard menu. Past skipped deliveries are not replayed; only new events are delivered.
* **Delete** - `DELETE .../endpoints/{endpointId}` soft-disables the endpoint. The endpoint and its event history remain visible for auditing.

### Send a test event

`POST .../endpoints/{endpointId}/test` (or **Send test event** in the endpoint's menu in the dashboard) enqueues a delivery with `type: "webhook.test"` and a small payload. The API returns `202` with an object that carries the `event_id`, the `delivery_ids`, and the `latest_delivery`. The signature flow is identical to production events, so a passing test verifies your verification code as well as connectivity.

A test event goes through the same delivery queue as other events, so it follows the [retry rules](#retries). If the endpoint is disabled, Foil skips the delivery, and the dashboard turns off **Send test event** for that endpoint.

## Event history and retention

Foil records subscribed events when your organization has an active endpoint
with an active subscription to that event type. Events with no active subscribers
are skipped and do not appear in webhook event history. Test events still
create an event for the selected endpoint.

Recorded events and their delivery diagnostics are retained for **7 days**.
Events with pending or in-flight deliveries remain until those deliveries finish;
they can therefore remain visible longer. Cleanup runs in batches, so expired
events can take additional time to disappear. This retention applies to webhook
history, not to the underlying session or scoring data.

## Authentication

Every Foil webhook is signed with HMAC-SHA256. Verify the signature before reading the body - without it, anyone who knows your URL can post arbitrary payloads.

### What gets signed

For every request, Foil computes:

```text theme={"dark"}
HMAC-SHA256(signing_secret, `${X-Foil-Timestamp}.${rawBody}`)
```

and sends the lowercase hex digest in `X-Foil-Signature`. The signing secret has the format `whsec_<base64url>` and is shown once when you create or rotate the endpoint.

The timestamp is the Unix epoch in seconds, as a string. Both headers are required; missing or malformed values must be rejected as 401.

> [!WARNING]
>
> Compute the HMAC over the **raw request bytes**, not over `JSON.stringify(req.body)`. Most JSON parsers reorder keys and strip whitespace, which produces a different digest and a guaranteed signature mismatch. Capture the raw body before any middleware parses it.

### Verify the signature

Each server SDK verifies a delivery and parses its envelope in one call. Pass the signing secret, both headers, and the raw request body. The helper checks the HMAC with a constant-time comparison, rejects a timestamp more than five minutes from your server's clock, and validates the envelope. It fails if any check fails, and your handler should then return `401`.

```javascript Node.js theme={"dark"}
const express = require('express');
const { verifyAndParseWebhookEvent } = require('@abxy/foil-server');

app.post('/webhooks/foil', express.raw({ type: 'application/json' }), (req, res) => {
  let event;
  try {
    event = verifyAndParseWebhookEvent({
      secret: process.env.FOIL_WEBHOOK_SECRET,
      timestamp: req.get('X-Foil-Timestamp') ?? '',
      signature: req.get('X-Foil-Signature') ?? '',
      rawBody: req.body,
    });
  } catch {
    return res.status(401).json({ error: 'Invalid webhook' });
  }

  handleFoilEvent(event);
  res.status(200).end();
});
```

```python Python theme={"dark"}
import os
from foil_server import verify_and_parse_webhook_event

@app.post("/webhooks/foil")
def foil_webhook():
    try:
        event = verify_and_parse_webhook_event(
            secret=os.environ["FOIL_WEBHOOK_SECRET"],
            timestamp=request.headers.get("X-Foil-Timestamp", ""),
            signature=request.headers.get("X-Foil-Signature", ""),
            raw_body=request.get_data(),
        )
    except ValueError:
        return {"error": "Invalid webhook"}, 401

    handle_foil_event(event)
    return "", 200
```

```go Go theme={"dark"}
import foil "github.com/abxy-labs/foil-server-go"

func foilWebhook(w http.ResponseWriter, r *http.Request) {
    body, err := io.ReadAll(r.Body)
    if err != nil {
        http.Error(w, "Bad request", http.StatusBadRequest)
        return
    }
    event, data, err := foil.VerifyAndParseWebhookEvent(foil.VerifyWebhookSignatureInput{
        Secret:    os.Getenv("FOIL_WEBHOOK_SECRET"),
        Timestamp: r.Header.Get("X-Foil-Timestamp"),
        Signature: r.Header.Get("X-Foil-Signature"),
        RawBody:   string(body),
    })
    if err != nil {
        http.Error(w, "Invalid webhook", http.StatusUnauthorized)
        return
    }

    handleFoilEvent(event, data)
    w.WriteHeader(http.StatusOK)
}
```

```ruby Ruby theme={"dark"}
require 'foil/server'

post '/webhooks/foil' do
  begin
    event = Foil::Server.verify_and_parse_webhook_event(
      secret: ENV.fetch('FOIL_WEBHOOK_SECRET'),
      timestamp: request.env['HTTP_X_FOIL_TIMESTAMP'].to_s,
      signature: request.env['HTTP_X_FOIL_SIGNATURE'].to_s,
      raw_body: request.body.read,
    )
  rescue ArgumentError, JSON::ParserError
    halt 401, { error: 'Invalid webhook' }.to_json
  end

  handle_foil_event(event)
  status 200
end
```

```php PHP theme={"dark"}
use Foil\Server\Webhooks;

try {
    $event = Webhooks::verifyAndParseWebhookEvent(
        secret: (string) getenv('FOIL_WEBHOOK_SECRET'),
        timestamp: $_SERVER['HTTP_X_FOIL_TIMESTAMP'] ?? '',
        rawBody: file_get_contents('php://input'),
        signature: $_SERVER['HTTP_X_FOIL_SIGNATURE'] ?? '',
    );
} catch (\InvalidArgumentException | \JsonException $e) {
    http_response_code(401);
    echo json_encode(['error' => 'Invalid webhook']);
    exit;
}

handleFoilEvent($event);
```

`handleFoilEvent` stands in for your own code that acts on `event.type` and `event.data`. The helpers accept only the event types their SDK version knows, so update the SDK before you subscribe an endpoint to a new event type.

Each SDK also exports the two steps separately. The verify helper returns a boolean, and the parse helper validates an envelope you have already verified. The verify helpers take an optional maximum age in seconds to change the five-minute window.

| SDK | Verify and parse | Verify only | Parse only | Maximum age |
| - | - | - | - | - |
| Node.js | `verifyAndParseWebhookEvent` | `verifyWebhookSignature` | `parseWebhookEvent` | `maxAgeSeconds` |
| Python | `verify_and_parse_webhook_event` | `verify_webhook_signature` | `parse_webhook_event` | `max_age_seconds` |
| Go | `foil.VerifyAndParseWebhookEvent` | `foil.VerifyWebhookSignature` | `foil.ParseWebhookEvent` | `MaxAgeSeconds` |
| Ruby | `Foil::Server.verify_and_parse_webhook_event` | `Foil::Server.verify_webhook_signature` | `Foil::Server.parse_webhook_event` | `max_age_seconds:` |
| PHP | `Webhooks::verifyAndParseWebhookEvent` | `Webhooks::verifyWebhookSignature` | `Webhooks::parseWebhookEvent` | `maxAgeSeconds:` |

### Verify without an SDK

If you don't use a server SDK, compute the HMAC yourself and compare it in constant time.

```javascript Node.js theme={"dark"}
const crypto = require('crypto');

app.post('/webhooks/foil', (req, res) => {
  const timestamp = req.headers['x-foil-timestamp'];
  const signature = req.headers['x-foil-signature'];
  const expected = crypto
    .createHmac('sha256', process.env.FOIL_WEBHOOK_SECRET)
    .update(`${timestamp}.${req.rawBody}`)
    .digest('hex');

  if (
    typeof signature !== 'string'
    || signature.length !== expected.length
    || !crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
  ) {
    return res.status(401).json({ error: 'Invalid signature' });
  }

  // Process the event...
  res.status(200).end();
});
```

```python Python theme={"dark"}
import hmac, hashlib, os

@app.post("/webhooks/foil")
def foil_webhook(request):
    timestamp = request.headers.get("X-Foil-Timestamp", "")
    signature = request.headers.get("X-Foil-Signature", "")
    expected = hmac.new(
        os.environ["FOIL_WEBHOOK_SECRET"].encode(),
        f"{timestamp}.".encode() + request.data,
        hashlib.sha256,
    ).hexdigest()

    if not hmac.compare_digest(signature, expected):
        return {"error": "Invalid signature"}, 401

    # Process the event...
```

```go Go theme={"dark"}
func foilWebhook(w http.ResponseWriter, r *http.Request) {
    body, _ := io.ReadAll(r.Body)
    timestamp := r.Header.Get("X-Foil-Timestamp")
    mac := hmac.New(sha256.New, []byte(os.Getenv("FOIL_WEBHOOK_SECRET")))
    mac.Write([]byte(timestamp + "."))
    mac.Write(body)
    expected := hex.EncodeToString(mac.Sum(nil))

    if !hmac.Equal([]byte(r.Header.Get("X-Foil-Signature")), []byte(expected)) {
        http.Error(w, "Invalid signature", 401)
        return
    }

    // Process the event...
}
```

```ruby Ruby theme={"dark"}
post '/webhooks/foil' do
  body = request.body.read
  timestamp = request.env['HTTP_X_FOIL_TIMESTAMP']
  signature = request.env['HTTP_X_FOIL_SIGNATURE']
  expected = OpenSSL::HMAC.hexdigest('SHA256', ENV['FOIL_WEBHOOK_SECRET'], "#{timestamp}.#{body}")

  halt 401, { error: 'Invalid signature' }.to_json unless Rack::Utils.secure_compare(signature, expected)

  # Process the event...
end
```

```php PHP theme={"dark"}
$body = file_get_contents('php://input');
$timestamp = $_SERVER['HTTP_X_FOIL_TIMESTAMP'] ?? '';
$signature = $_SERVER['HTTP_X_FOIL_SIGNATURE'] ?? '';
$expected = hash_hmac('sha256', "{$timestamp}.{$body}", getenv('FOIL_WEBHOOK_SECRET'));

if (!hash_equals($signature, $expected)) {
    http_response_code(401);
    echo json_encode(['error' => 'Invalid signature']);
    exit;
}

// Process the event...
```

Always compare with a constant-time helper (`crypto.timingSafeEqual`, `hmac.compare_digest`, `hmac.Equal`, `Rack::Utils.secure_compare`, `hash_equals`) - naive `==` leaks information about partial matches.

### Replay protection

The timestamp is signed, so an attacker cannot reuse a captured request with a forged body. To also reject **replays of the original request**, reject anything whose timestamp is more than a few minutes old. The SDK helpers do this for you. Without an SDK, add the check yourself:

```javascript theme={"dark"}
const skewSeconds = Math.abs(Date.now() / 1000 - Number(timestamp));
if (!Number.isFinite(skewSeconds) || skewSeconds > 5 * 60) {
  return res.status(401).json({ error: 'Stale webhook' });
}
```

Five minutes is a comfortable bound; tighten it if you have strict clock sync. Also dedupe by the envelope `id` to drop legitimate retries - see [Idempotency](#idempotency).

### Rotating secrets

`POST .../endpoints/{endpointId}/rotations` (or **Rotate secret** in the endpoint's menu in the dashboard) returns a new `signing_secret` and immediately uses it for outgoing deliveries. Foil signs each attempt with the secret that is current when it makes the attempt, so a retry that starts after you rotate uses the new secret. Rotate when:

* a teammate with access to the secret leaves
* the secret may have been logged or committed
* on a regular schedule (annually is a reasonable default)

To rotate without dropping in-flight deliveries, do an overlap window:

1. Add the new secret as a second verifier in your code, alongside the current one.
2. Deploy. Both signatures now verify.
3. Rotate via the API. Foil signs new requests with the new secret.
4. After the retry window ends, drop the old secret from your code and redeploy. Foil finishes all attempts for an event within about a minute of the first attempt, plus any delay in the delivery queue, so waiting 10 minutes leaves a wide margin.

```javascript theme={"dark"}
const secrets = [
  process.env.FOIL_WEBHOOK_SECRET_NEW,
  process.env.FOIL_WEBHOOK_SECRET_OLD,
].filter(Boolean);

const valid = secrets.some((secret) => {
  const expected = crypto
    .createHmac('sha256', secret)
    .update(`${timestamp}.${req.rawBody}`)
    .digest('hex');
  return signature.length === expected.length
    && crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
});
```

## Delivery

### The request

Every webhook is an HTTP `POST` with a JSON body and these headers:

| Header | Description |
| - | - |
| `Content-Type` | Always `application/json`. |
| `X-Foil-Event` | The event ID - same as `id` in the [envelope](#envelope). Use this for idempotency. |
| `X-Foil-Event-Type` | The event type, e.g. `session.result.persisted`. Lets you route without parsing the body. |
| `X-Foil-Timestamp` | Unix timestamp in seconds, as a string. Part of the signature base string. |
| `X-Foil-Signature` | HMAC-SHA256 hex digest. See [Authentication](#authentication). |

There is no fixed source IP range and no IP allowlist. Authenticate via the signature, not the network.

### What counts as success

* **2xx** - delivery succeeds. The endpoint will not be retried for this event.
* **anything else** - delivery fails and is retried (up to the limit below). This includes non-2xx statuses, connection errors, DNS failures, and timeouts. Foil doesn't follow redirects, so a 3xx response counts as a failure.
* **A response body over 256 KB** - the attempt fails even if the status is 2xx. Foil stops reading at 256 KB and abandons the attempt.

The per-attempt timeout is **10 seconds**. The deadline covers DNS resolution, the connection, and the complete response, and it doesn't reset while your server is sending data. If your handler takes longer, do the heavy work asynchronously: enqueue a job, then return 200 immediately.

Foil stores up to the first 4000 characters of the response body in the delivery log. Return a short body, or none.

### Retries

If an attempt fails, Foil retries the delivery from a worker queue, for up to **5 attempts in total**. It waits 1 second after the first failed attempt, then 2, 4, and 8 seconds after the next three. That is exponential backoff that doubles from a 1-second base. Each attempt can take up to 10 seconds, so all five attempts finish within about a minute of the first. When the worker queue is busy, the actual delay can extend, so treat all timing as a lower bound and design for "delivered eventually" rather than "delivered on a fixed schedule."

After the 5th failed attempt the delivery moves to terminal `failed` status and stops retrying. Foil has no manual redelivery, in the dashboard or the API. To recover from a failed delivery, retrieve the event with `GET /v1/organizations/{organizationId}/events/{eventId}` while it is still within the [retention period](#event-history-and-retention) and process its `data`, or read the session with the Sessions API. Sending a test event checks that your endpoint is healthy again, but it doesn't redeliver earlier events.

Delivery status values you'll see in the dashboard and the API:

| Status | Meaning |
| - | - |
| `pending` | Queued, not yet attempted (or scheduled retry). |
| `delivering` | A worker is currently sending the request. |
| `succeeded` | The endpoint returned 2xx. |
| `failed` | All retries exhausted with non-2xx / errors. |
| `skipped` | The endpoint was disabled or deleted before delivery. |

### Idempotency

You may receive the **same event ID more than once** - retries after a transient 5xx, network blips, or worker reschedules. Make your handler idempotent on `X-Foil-Event`:

```javascript theme={"dark"}
async function handleEvent(envelope) {
  const eventId = envelope.id;
  const inserted = await db.query(
    `INSERT INTO webhook_events (id) VALUES ($1) ON CONFLICT DO NOTHING`,
    [eventId],
  );
  if (inserted.rowCount === 0) return; // already processed

  // ... do the work
}
```

Foil also dedupes internally per `(event_id, endpoint_id)`, so the same event never produces parallel deliveries to one endpoint. But your handler must still tolerate retries of the same event ID over time.

A session produces at most one `session.result.persisted` event, so `data.session.id` also works as a key for that event.

### Event log

Every event is recorded with its delivery attempts. View it in two places:

* **Dashboard** - the **Delivery history** card on the **Webhooks** page lists recent deliveries with the event type, delivery status, attempt count, and last update time. It refreshes automatically. The dashboard doesn't show response codes or response bodies, and it has no filters.
* **API** - `GET /v1/organizations/{organizationId}/events` returns event resources with nested deliveries, including the latest response code and response body. Retrieve one event with `GET /v1/organizations/{organizationId}/events/{eventId}`. Both require a live secret key with the `webhooks:read` scope.

```bash theme={"dark"}
curl 'https://api.usefoil.com/v1/organizations/org_.../events?endpoint_id=we_...&type=session.result.persisted&limit=50' \
  -H "Authorization: Bearer sk_live_..."
```

Supported list filters:

| Query param | Description |
| - | - |
| `endpoint_id` | Only return events that produced a delivery for this endpoint. |
| `type` | Only return events of this type. Includes `webhook.test` for test sends. |
| `limit` | 1–200, default 50. |

Events are ordered newest first. The list has no `cursor`. It returns at most `limit` events in one page, and `pagination.has_more` is always `false`. An unknown `type`, or a `limit` outside the range, returns `422`.

Each event resource looks like:

```json theme={"dark"}
{
  "object": "event",
  "id": "wevt_0123456789abcdef0123456789abcdef",
  "type": "session.result.persisted",
  "subject": { "type": "session", "id": "sid_..." },
  "data": { ... },
  "webhook_deliveries": [
    {
      "object": "webhook_delivery",
      "id": "wdlv_0123456789abcdef0123456789abcdef",
      "event_id": "wevt_...",
      "endpoint_id": "we_...",
      "event_type": "session.result.persisted",
      "status": "succeeded",
      "attempts": 1,
      "response_status": 200,
      "response_body": "ok",
      "error": null,
      "created_at": "2026-03-24T20:00:05.000Z",
      "updated_at": "2026-03-24T20:00:06.000Z"
    }
  ],
  "created_at": "2026-03-24T20:00:05.000Z"
}
```

| Field | Description |
| - | - |
| `id` | Event ID - also sent as `X-Foil-Event` and as the envelope `id`. |
| `type` | The event type. |
| `subject.type` / `subject.id` | The resource the event is about (e.g. `session` / `sid_...`). |
| `data` | The same `data` object delivered in the webhook envelope. |
| `webhook_deliveries[]` | One entry per endpoint subscribed at the time of fan-out. Each entry tracks attempts, the latest `response_status` and `response_body` (truncated to 4000 chars), the most recent `error`, and a `status` of `pending`, `delivering`, `succeeded`, `failed`, or `skipped`. |
| `created_at` | When the event was recorded. |

### Local development

Foil refuses to deliver to private IPs in production. To develop against your laptop, use a tunnel (`ngrok`, `cloudflared`, etc.) and register the tunnel's public URL as the endpoint. The signature flow and payloads are identical to production.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.