# Receive webhooks

> Canonical URL: https://docs.mountaya.com/en/sdks/typescript/webhooks/
> Last updated: 2026-11-27
> Rules for agents: https://docs.mountaya.com/llms.txt#rules-for-agents

Verify a Mountaya webhook delivery with constructWebhookEvent, handle each event by its type, rotate the signing secret, and test your receiver.

Mountaya sends your server a signed [webhook event](https://docs.mountaya.com/en/webhooks.md) for each change in your organization. `constructWebhookEvent` checks the signature and hands you the event, typed by its `type`.

## Verify a delivery

Pass the raw body, the `Mountaya-Signature` header and your endpoint's secret:

```ts
import {
  constructWebhookEvent,
  MountayaWebhookSignatureError,
  type WebhookEvent,
} from "@mountaya/client/admin";

const secret = process.env.MOUNTAYA_WEBHOOK_SECRET ?? "";

// A route handler that receives a Fetch API Request, as Next.js, Hono, Bun and Deno do.
export async function POST(request: Request): Promise<Response> {
  let event: WebhookEvent;
  try {
    event = await constructWebhookEvent(
      await request.text(),
      request.headers.get("Mountaya-Signature"),
      secret,
    );
  } catch (error) {
    if (error instanceof MountayaWebhookSignatureError) {
      return new Response(error.reason, { status: 400 });
    }
    throw error;
  }

  console.log(event.id, event.type);
  return new Response(null, { status: 200 });
}
```

Read the body before any JSON parser does: a body parsed and written out again no longer matches its signature. [Verify webhook signatures](https://docs.mountaya.com/en/webhooks/signatures.md) explains the scheme.

- `constructWebhookEvent(rawBody, signatureHeader, secret, options?)` is exported by `@mountaya/client/admin`, beside `MountayaWebhookSignatureError`, `WebhookEvent`, `WebhookSignatureFailure` and `ConstructWebhookEventOptions`. It answers a promise: the MAC is computed with Web Crypto, which Node, browsers, workers and edge runtimes provide.
- `rawBody` is a `string` or a `Uint8Array` (a Node `Buffer` is one), exactly as it arrived: `await request.text()` on a Fetch API `Request`, `express.raw({ type: "application/json" })` in Express. `signatureHeader` may be `null` or `undefined`, as `request.headers.get` answers it. `secret` is the endpoint's signing secret, `whsk_` included, answered once by `postOrganizationWebhookEndpoint`.
- It reads the header first, then the signature, then the time, so a forged delivery is refused for its signature whatever time it claims. It throws `MountayaWebhookSignatureError` (a `MountayaError`) whose `reason` is `missing-header`, `malformed-header` (not `t=<unix seconds>,v1=<signature>`), `signature` (no `v1` matches this body under this secret) or `timestamp` (the signature verifies and `t` stands more than the tolerance from your clock, either way). Answer each with a `400`: Mountaya retries a failed attempt, so a wrong secret or clock costs an attempt, not the event.
- It throws `MountayaConfigurationError` for a body that is no string or `Uint8Array`, a secret that does not start with `whsk_`, a `toleranceSeconds` that is no finite number from 0, a `now` that is no valid `Date`, a runtime with no Web Crypto, and, once the delivery verifies, a body that is not a JSON object. It names no `reason`: answer a request it refuses with a `400` as well, and act on nothing.
- `options`: `toleranceSeconds` (default 300), and `now`, the instant your clock reads (default: the machine's wall clock, read once the signature verifies).
- Only the body is signed. The `Mountaya-Event-Id`, `Mountaya-Event-Type` and `Mountaya-Delivery-Attempt` headers restate it for routing: read `id` and `type` from the event.
- Keep the secret on the server that receives deliveries, the one place this function runs. The admin unit holds no secret key, but a page has no business verifying deliveries.

## Handle an event

Switch on `event.type`, and `data` narrows to what that type carries:

```ts
import type { WebhookEvent } from "@mountaya/client/admin";

export const handle = (event: WebhookEvent): void => {
  switch (event.type) {
    case "organization.member.updated":
      console.log(event.data.object.role, event.data.previous_attributes?.role);
      break;
    case "collection.deleted":
      console.log(`collection ${event.data.object.id} deleted`);
      break;
  }
};
```

An event can arrive twice, and in any order. Store what you act on keyed by `event.id`, and answer `200` within 10 seconds, before any slow work.

- `WebhookEvent` is the union of every event type this release knows, each tying its `type` to its `data`. `WebhookEvent<"zone.updated">` names the event of one type, for a handler written for it. `RestSchema` of `@mountaya/client` keeps the contract's untied envelope, as `getOrganizationWebhookEvents` lists it.
- The envelope: `id` (a UUIDv7, the key to deduplicate on), `object` (`webhook_event`), `type`, `api_version`, `created_at`, `organization_id`, `task`, `related_object` (`type`, `id`), `data` (`object`, and `previous_attributes` on the types that carry it), `request` (`{ id }` or `null`), `actor`. See [the envelope](https://docs.mountaya.com/en/webhooks.md#envelope) and the [event reference](https://docs.mountaya.com/en/webhooks/events/itinerary.md).
- Instants are `Date`s: `created_at`, those of `data.object`, and those `data.previous_attributes` holds. A member its type marks required and nullable that the delivery leaves out reads `null`; `previous_attributes` holds only what was sent.
- Delivery is at least once and in no promised order: order one resource's events by the `version` its object carries, or read the resource. An attempt not answered with a `2xx` within 10 seconds is repeated, for about 72 hours. See [delivery and retries](https://docs.mountaya.com/en/webhooks/delivery.md).
- `data.object` is lean: identifiers and bounded figures, never geometry, a token or a secret. Read the resource for anything more.

## Ignore unknown events

A type added after your release arrives with that type, and reaches the `default` of your `switch`. Acknowledge it, and do nothing:

```ts
import type { WebhookEvent } from "@mountaya/client/admin";

export const route = (event: WebhookEvent): Response => {
  switch (event.type) {
    case "organization.member.deleted":
      console.log(`${event.data.object.user_id} left`);
      return new Response(null, { status: 200 });
    default:
      // A type you do not handle, or one newer than this release.
      return new Response(null, { status: 200 });
  }
};
```

- An event of a type a newer contract added is answered with the type it arrived with, typed as this release types `WebhookEvent`, so no `case` of a known type reaches it. Never answer it with a non-`2xx`: a failed attempt is repeated, and an endpoint failing for 72 hours is disabled.
- An endpoint is sent only the types its `enabled_events` names. `*` includes every public type, those added later among them; a family followed by `.*` includes the types added to that family.

## Rotate the secret

Rotate an endpoint's secret in the Mountaya app, under **Organization → Webhooks**. For up to 7 days, each delivery carries a signature for the old secret and the new one, and either verifies. Deploy the new secret in `MOUNTAYA_WEBHOOK_SECRET` before the overlap ends.

If a secret leaked, rotate it with no overlap. Every earlier secret stops at once.

- During the overlap the `Mountaya-Signature` header carries one `v1` per secret in force, in no promised order. `constructWebhookEvent` accepts a delivery when any `v1` matches the secret it is handed, so a receiver holding either secret verifies with no code change.
- One overlap at a time: another rotation keeping an overlap is refused while the previous secret still signs. A rotation with no overlap is always taken.
- No API operation reveals or rotates a secret: an owner or an admin does it in the Mountaya app, which records `organization.webhook_endpoint.secret_rotated`. See [rotation](https://docs.mountaya.com/en/webhooks/signatures.md#rotation).

## Test your receiver

Run the contract's [published test vectors](https://docs.mountaya.com/en/webhooks/signatures.md#test-vectors) through your receiver's verification, with `now` pinned to each vector's time:

```ts
import { readFileSync } from "node:fs";
import { constructWebhookEvent } from "@mountaya/client/admin";
import { expect, test } from "vitest";

interface SignatureVector {
  readonly body: string;
  readonly expect: { readonly reason?: string; readonly valid: boolean };
  readonly header: string;
  readonly name: string;
  readonly now: number;
  readonly secret: string;
}

// signature-vectors.json, downloaded from the contract beside this test.
const { cases }: { cases: SignatureVector[] } = JSON.parse(
  readFileSync("signature-vectors.json", "utf8"),
);

for (const vector of cases) {
  test(vector.name, async () => {
    const verifying = constructWebhookEvent(vector.body, vector.header, vector.secret, {
      now: new Date(vector.now * 1000),
    });

    if (vector.expect.valid) {
      await expect(verifying).resolves.toMatchObject({ type: "organization.member.updated" });
    } else {
      await expect(verifying).rejects.toMatchObject({ reason: vector.expect.reason });
    }
  });
}
```

The five cases cover a valid delivery, both secrets of a rotation, a tampered body and a replay.

To send a real test event to your endpoint, use the Mountaya app or [`postOrganizationWebhookDelivery`](https://docs.mountaya.com/en/sdks/typescript/admin.md#webhook-endpoints).

- `now` is the instant your receiver's clock reads, so a test pins the time with it rather than faking the system's clock. A `now` more than `toleranceSeconds` from `t` refuses the delivery with the reason `timestamp`; a changed body or another secret refuses it with `signature`.
- The vectors file is `/schemas/v0.9.0/openapi/api/webhooks/signature-vectors.json` on this site: `{ description, algorithm, tolerance_seconds, cases }`, each case `{ name, description, secret, now, header, body, signatures, expect: { valid, reason? } }`, plus `signed_body` where the body was changed on the way. The cases are `valid`, `rotation-new-secret`, `rotation-previous-secret`, `tampered-body` (`reason` `signature`) and `outside-tolerance` (`reason` `timestamp`); each verified body is an `organization.member.updated` event. Each `now` is in Unix seconds: pass `new Date(now * 1000)`. A `reason` is the `WebhookSignatureFailure` `constructWebhookEvent` throws with.
- To sign a body of your own in a test, compute the lowercase hexadecimal HMAC-SHA256 of `<t>.<body>` with Web Crypto, keyed by any secret starting with `whsk_`, and send `t=<t>,v1=<signature>` ([testing](https://docs.mountaya.com/en/sdks/typescript/testing.md#webhooks) shows it).
- A test event (`postOrganizationWebhookDelivery({ organization_id, body: { webhook_endpoint_id, test: { type } } })`) carries the contract's example payload for the type, with an `id` of its own, is delivered once without retries, and is listed by no `getOrganizationWebhookEvents`. An endpoint is sent a test of any type, whether or not its `enabled_events` names it. See [test your endpoint](https://docs.mountaya.com/en/webhooks/testing.md).

## Next steps

- [Manage an organization](https://docs.mountaya.com/en/sdks/typescript/admin.md): Create the endpoint, and resend an event.
- [Webhooks](https://docs.mountaya.com/en/webhooks.md): The envelope, delivery and every event type.
