> For the complete documentation index, see [llms.txt](https://docs.fastn.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.fastn.ai/reference/sdk/events.md).

# Events

Receive signed events about connections, setup links and app changes, verify them with parseEvent, and manage deliveries.

fastn can tell your backend when something happens: a customer connected an app, a setup link was used, or a record changed in a customer's app. You register an https endpoint once (an **event subscription**). fastn then sends each event to it as a signed `POST`.

***

## Register your endpoint

```typescript
const hook = await fastn.webhooks.create({
  url: "https://hooks.example.com/fastn/events",
  eventTypes: ["connection.connected", "connection.revoked", "connection.expired", "setup_link.completed", "setup_link.expired", "connector.event", "unified.event"],
  description: "Production",
});

const webhookId = hook.id;     // esub_…
const secret = hook.secret;    // whsec_…: shown once, store it now
```

`fastn.webhooks` answers the subscription itself (no `data` wrapper). For one customer only, create it on the customer instead: `customer.api.events.createEventSubscription({ … })` fills in the customer for you, and that endpoint receives that customer's events alone.

| Field            | Required | Meaning                                                                                                                                                                               |
| ---------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `url`            | Yes      | Your https endpoint. An `http` URL is refused with `400 VALIDATION_ERROR`; a private or internal address is refused with `400 EVENT_SUBSCRIPTION_URL_NOT_ALLOWED`.                    |
| `eventTypes`     | No       | Which events to send (table below). Leave it out for every connection and setup link event. `connector.event`, `unified.event` and `workflow.event` are sent only when you list them. |
| `connectors`     | No       | `connector.event` only: just events from these apps (slug or connector id), for example `["hubspot"]`.                                                                                |
| `providerEvents` | No       | `connector.event` only: just these app event names, for example `["contact.creation"]`.                                                                                               |
| `entities`       | No       | `unified.event` only: just these entities, as `category/entity`, for example `["crm/contact"]`.                                                                                       |
| `workflowEvents` | No       | `workflow.event` only: just these event names (the names your workflows pass to `fastn.events.emit`). Empty means every name.                                                         |
| `description`    | No       | Your label.                                                                                                                                                                           |
| `enabled`        | No       | Default `true`.                                                                                                                                                                       |

Answer: the subscription itself, `{ id, url, orgId, eventTypes, connectors, connectorCategories, providerEvents, entities, workflowEvents, payloadTemplate, enabled, description, createdBy, createdAt, updatedAt, secret }`. The raw operation `fastn.events.createEventSubscription` answers the same object wrapped as `{ data: { … } }`. The `secret` is returned **only here**: reading the subscription later never shows it.

***

## Event types

| `type`                 | Sent when                                                                                                            | Fields on top of the common ones                                                                                                                                                                                                                                                    |
| ---------------------- | -------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `connection.connected` | A customer connected an account, or signed in to it again.                                                           | `app`, `connectionId`, `connectionName`, and when known `account`, `setupLinkId`, `metadata`                                                                                                                                                                                        |
| `connection.revoked`   | An account was removed.                                                                                              | `app`, `connectionId`                                                                                                                                                                                                                                                               |
| `connection.expired`   | The app rejected the stored login; the customer must sign in again.                                                  | `app`, `connectionId`, `reason` (for example `needs_reauth`)                                                                                                                                                                                                                        |
| `setup_link.completed` | The customer finished a setup link.                                                                                  | `setupLinkId`, `installationId`, `connections` (app slug → `connectionId`), `metadata`                                                                                                                                                                                              |
| `setup_link.expired`   | A setup link expired unused.                                                                                         | `setupLinkId`, `metadata`                                                                                                                                                                                                                                                           |
| `connector.event`      | A change in a customer's app, for example a new HubSpot contact. Needs an [app event trigger](#app-events).          | `app`, `connector`, `connectionId`, `event` (the app's event name), `accountId`, `triggerId`, `payload` (the app's own body)                                                                                                                                                        |
| `unified.event`        | The same app change, as a unified record. Needs an [app event trigger](#app-events).                                 | `app`, `connector`, `connectionId`, `category`, `entity`, `action` (`created`, `updated` or `deleted`), `remoteId` (the record id in the app), `providerEvent`, `triggerId`, and `record` (the unified record `{ id, provider, data }`) or `recordError` (why it could not be read) |
| `workflow.event`       | A workflow sent an event with `fastn.events.emit`. Opt in: sent only when you list it, filtered by `workflowEvents`. | `event` (the name the workflow gave it), `workflowId`, `executionId`, `payload` (the data the workflow sent), and when set `app`, `connector`, `installationId`                                                                                                                     |
| `endpoint.test`        | You sent a test with `testEventSubscription`.                                                                        | None                                                                                                                                                                                                                                                                                |

Every event carries `id` (`evt_…`), `type`, `occurredAt`, and `tenantRef` and `orgId` (your customer id: match on this). `metadata` is the object you set on the setup link.

```json
{
  "id": "evt_3f9a0c2b7d4e4b8e9a1c5d6e7f8a9b0c",
  "type": "setup_link.completed",
  "occurredAt": "2026-10-26T00:01:03.486Z",
  "tenantRef": "acme_customer_42",
  "orgId": "acme_customer_42",
  "setupLinkId": "stp_1a2b3c4d5e6f",
  "installationId": "inst_…",
  "connections": { "hubspot": "ucl:…:default" },
  "metadata": { "flowId": "flow_123" }
}
```

***

## Receive and verify events

Each delivery carries these headers:

| Header               | Meaning                                                                                             |
| -------------------- | --------------------------------------------------------------------------------------------------- |
| `X-Fastn-Signature`  | `sha256=` + HMAC-SHA256 of `<timestamp>.<raw body>`, keyed with your `whsec_…` secret.              |
| `X-Fastn-Timestamp`  | Unix seconds when the delivery was signed.                                                          |
| `X-Fastn-Event-Id`   | The event id. It stays the same on every retry.                                                     |
| `X-Fastn-Redelivery` | `true` on an automatic retry. A replay starts the count again, so its first send does not carry it. |

`parseEvent` checks the signature, refuses deliveries older than five minutes, and returns the event. Give it the **raw** body exactly as received: a re-serialized object changes the bytes and fails the check.

```typescript
import express from "express";
import { parseEvent } from "@fastn-ai/sdk";

const app = express();
const seen = new Set<string>();

app.post("/fastn/events", express.raw({ type: "application/json" }), (req, res) => {
  let event;
  try {
    event = parseEvent(process.env.FASTN_EVENT_SECRET!, req.headers, req.body);
  } catch {
    res.status(401).end();           // wrong signature, altered body, or too old
    return;
  }

  if (event.id && seen.has(event.id)) {
    res.status(200).end();           // a retry of an event you already handled
    return;
  }
  if (event.id) seen.add(event.id);

  res.status(200).end();             // answer fast, then do the work

  switch (event.type) {
    case "connection.connected":
      console.log(event.tenantRef, "connected", event.app, event.connectionId);
      break;
    case "setup_link.completed":
      console.log(event.tenantRef, "finished setup", event.setupLinkId, event.metadata);
      break;
  }
});

app.listen(3000);
```

In production keep the seen ids in your database rather than in memory.

| Function                                                | Input                                                                                                                               | Answer                                                                                                                                                     |
| ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `parseEvent(secret, headers, rawBody, opts?)`           | `secret`: your `whsec_…`. `headers`: the request headers (Node, Fetch `Headers`, or a plain object). `rawBody`: string or `Buffer`. | The event object plus `headers` (`timestamp`, `signature`, `eventId`, `redelivery`). Throws when the signature does not match or the timestamp is too old. |
| `verifyEventSignature(secret, headers, rawBody, opts?)` | Same as above.                                                                                                                      | `true` or `false`, without parsing.                                                                                                                        |
| `readEventHeaders(headers)`                             | The request headers.                                                                                                                | `{ timestamp, signature, eventId, redelivery }`                                                                                                            |
| `signEventBody(secret, timestamp, rawBody)`             |                                                                                                                                     | The signature string fastn would send. Useful in your own tests.                                                                                           |

`opts.toleranceSeconds` changes the five-minute window (default 300; `0` turns the age check off).

Test your handler without fastn by signing a body yourself:

```typescript
import { parseEvent, signEventBody } from "@fastn-ai/sdk";

const body = JSON.stringify({ id: "evt_123", type: "endpoint.test", tenantRef: "acme_customer_42" });
const ts = Math.floor(Date.now() / 1000);
const headers = {
  "x-fastn-timestamp": String(ts),
  "x-fastn-signature": signEventBody("whsec_test", ts, body),
  "x-fastn-event-id": "evt_123",
};

const event = parseEvent("whsec_test", headers, body);   // { id: "evt_123", type: "endpoint.test", … }
```

***

## Deliveries and retries

fastn retries a delivery with growing gaps for 24 hours, until your endpoint answers `2xx`. After that the delivery is marked `dead`. The event id never changes, so drop repeats by id.

| Do this           | SDK                                                                                                                 | Answer                                                                                                                                                                                                                                                                    |
| ----------------- | ------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Send a test event | `fastn.webhooks.test(id)`                                                                                           | `{ eventId, status: "queued" }`. Sends one `endpoint.test` event.                                                                                                                                                                                                         |
| See deliveries    | `fastn.webhooks.deliveries(id, { limit? })`                                                                         | `[ { id, eventId, type, status, attempts, lastStatus, lastError, nextAttemptAt, createdAt, deliveredAt } ]`, newest first. `limit` defaults to 50, at most 200. `status` is `pending`, `delivered` or `dead`; the API does not filter on it, so filter the list yourself. |
| Send one again    | `fastn.webhooks.replay(deliveryId)`                                                                                 | `{ id, status: "pending" }`. Sends the delivery again with the same event id, on a fresh retry schedule (attempts start again at 0). Works for `dead` deliveries too.                                                                                                     |
| Pause or change   | `fastn.webhooks.update(id, { url?, eventTypes?, connectors?, providerEvents?, entities?, description?, enabled? })` | The updated subscription. With `enabled: false`, deliveries are held and checked again every 5 minutes; a delivery still held 24 hours after it was created is marked `dead`. Enable the webhook again within 24 hours, or replay the dead deliveries.                    |
| Read              | `fastn.webhooks.get(id)` / `fastn.webhooks.list()`                                                                  | The subscription(s), without the secret.                                                                                                                                                                                                                                  |
| New secret        | `fastn.webhooks.rotateSecret(id)`                                                                                   | A new secret, returned once. Deliveries after this are signed with it.                                                                                                                                                                                                    |
| Remove            | `fastn.webhooks.delete(id)`                                                                                         | `{ id, deleted: true }`. Queued deliveries go with it.                                                                                                                                                                                                                    |

The same calls exist as raw operations under `fastn.events` (`createEventSubscription`, `listEventDeliveries`, …) with `{ data }` answers.

***

## App events: watch a customer's app

`connector.event` and `unified.event` come from changes inside a customer's app. fastn listens for them only after you turn them on for that customer's account:

```typescript
const watch = await customer.watch("hubspot", ["contact.created", "contact.updated", "deal.stageChanged"]);
// watch.id, watch.events (the app's own event ids)

const events = await customer.watchableEvents("hubspot");     // the app's own event rows: { id, label, description, payloadSchema }
const watches = await customer.watches("hubspot");            // the customer's watches on that app (every page)
await customer.unwatch("hubspot");                            // or unwatch(watch.id)
```

| Method                                                              | Meaning                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `customer.watch(app, events, { accountId?, connectionId?, name? })` | Turns the events on. Events are named in plain words (`contact.created`, `deal.stageChanged`) or as the app names them; an unknown name is `400 EVENT_NOT_FOUND` with the valid list. The customer's account on the app is found from their connections: none is `404 CONNECTION_NOT_FOUND`, several is `409 CONNECTION_AMBIGUOUS` (pass `connectionId`). Two plain names that map to one app event are sent once; a `connectionId` of another app is `400 CONNECTION_MISMATCH`. `accountId` is the app's own account id when the app needs one (the HubSpot portal id). |
| `customer.watchableEvents(app)`                                     | The app's own event rows, `{ id, label, description, payloadSchema }`. The plain names `watch` accepts (`contact.created`) are SDK aliases and are not in this list.                                                                                                                                                                                                                                                                                                                                                                                                     |
| `customer.watches(app?)`                                            | The customer's watches, every page.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `customer.unwatch(app)` / `customer.unwatch(watchId)`               | Removes the watches on an app, or one watch; answers the ids removed. A watch id that is not this customer's is `404 WATCH_NOT_FOUND`.                                                                                                                                                                                                                                                                                                                                                                                                                                   |

HubSpot has no stage-only event: `deal.stageChanged` maps to `deal.propertyChange`; filter on `propertyName === "dealstage"` in the event.

Each change then arrives as a `connector.event` (the app's own body) and a `unified.event` (the record in unified fields) on every webhook that lists those types.

### Underneath: app event triggers

`watch` creates an **app event trigger**. The raw calls are still there when you need them. First list the events an app offers:

```typescript
const conns = await customer.connections();
const hubspot = (conns.data ?? []).find((c: any) => c.connector?.slug === "hubspot");

const offered = await fastn.events.listConnectorEvents({ connectorId: String(hubspot?.connectorId) });
// offered.data.events = [ { id: "contact.creation", label: "Contact Created", description, payloadSchema }, … ]

// Then create the trigger for that account
await customer.api.events.createAppEventTrigger({
  name: "Acme HubSpot contacts",
  connectorId: String(hubspot?.connectorId),
  connectorName: "HubSpot",
  events: [
    { id: "contact.creation", label: "Contact Created" },
    { id: "contact.propertyChange", label: "Contact Property Changed" },
  ],
  type: "WEBHOOK",
  accountId: "<the account id in the app, for example the HubSpot portal id>",
  connectionId: String(hubspot?.id),
  status: "ACTIVE",
});
```

| Field           | Required                 | Meaning                                                                            |
| --------------- | ------------------------ | ---------------------------------------------------------------------------------- |
| `name`          | Yes                      | Your label.                                                                        |
| `connectorId`   | Yes                      | The app's id: `connectorId` of the connection.                                     |
| `connectorName` | Yes                      | The app's name, for example `HubSpot`.                                             |
| `events`        | Yes                      | The app events to receive, each `{ id, label }`, from `listConnectorEvents`.       |
| `connectionId`  | For a customer's account | The connection the events are for.                                                 |
| `accountId`     | When the app needs it    | The app's own account id, for example the HubSpot portal id or a Facebook Page id. |
| `type`          | No                       | `WEBHOOK` or `POLLING`.                                                            |
| `status`        | No                       | `ACTIVE` or `DISABLED`.                                                            |

List triggers with `fastn.events.listAppEventTriggers()` and remove one with `fastn.events.deleteAppEventTrigger({ id })`. See also [App event triggers](https://docs.fastn.ai/build/integrations/triggers/app-events.md) and, for the events fastn received, [Events](https://docs.fastn.ai/operate/operate/events.md).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.fastn.ai/reference/sdk/events.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
