Get started
TypeScript SDK
Fetch data

Receive webhooks

Receive webhooks

Mountaya sends your server a signed webhook event 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:

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 explains the scheme.

Handle an event

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

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.

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:

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 });
  }
};

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.

Test your receiver

Run the contract's published test vectors through your receiver's verification, with now pinned to each vector's time:

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.

Next steps

Last updated