---
title: Receive webhooks
description: Take a signed request from another service, check its signature, answer at once and do the work later, once for each delivery.
related:
  - /http/serve-http-routes
  - /background/run-durable-work
  - /recipes/process-webhooks-reliably
---

A payment provider or a code host tells your app about an event by calling a URL you give it. It signs the body, waits only a short while for your answer, and sends the same event again when it gets no answer in time.

A webhook needs three things from your app: a route that takes the raw request, a check of the signature, and work that runs once however many times the event arrives.

## Take a webhook on a route

Give a handler a route with `auth: "none"`, since the sender has no Luna key, and `args: t.request()`, to read the body exactly as it was signed. A [stateless luna](/lunas/write-stateless-lunas) fits, because many deliveries can run at once.

```ts luna/lunas/payments.ts
import { defineLuna, t } from "luna";
import { verifyWebhook } from "luna/auth";
import { Shop } from "./shop.ts";

export const Payments = defineLuna({
  name: "Payments",
  stateless: true,
  handlers: (h) => ({
    hook: h({ args: t.request(), route: { path: "POST /webhooks/payments", auth: "none" } }, async (ctx, req) => {
      const body = await req.text();
      const secret = ctx.env.PAYMENTS_SECRET;
      if (!secret || !verifyWebhook(body, req.headers.get("x-signature") ?? "", secret)) {
        return new Response("bad signature", { status: 401 });
      }
      const event = JSON.parse(body) as { id: string; shop: string; amount: number };
      await ctx.call(Shop, { id: event.shop }).paid({ delivery: event.id, amount: event.amount });
      return new Response(null, { status: 204 });
    }),
  }),
});
```

Give the sender the route's address: the one [`luna status`](/cli/status) prints after `Routes at`, followed by `/webhooks/payments`. [Serve HTTP routes](/http/serve-http-routes) covers routes in full.

## Check the signature

[`verifyWebhook`](/sdk/auth) from `luna/auth` says whether a signature is the HMAC-SHA256 of the body with your secret. It compares in constant time and returns `false` for any signature that does not match.

Keep the secret the sender gives you as a secret of the environment. The handler reads it from `ctx.env`. [`luna secrets set`](/cli/secrets) reads the value from standard input.

```bash
luna secrets set PAYMENTS_SECRET
```

Senders differ in how they write the signature. Pass options to match yours.

| Option | Does |
| --- | --- |
| `encoding` | `"hex"`, the default, or `"base64"` |
| `prefix` | Text before the signature, such as `"sha256="`. The signature must start with it |
| `timestamp` | The sender's timestamp in Unix seconds. The signed text is then `<timestamp>.<body>` |
| `toleranceSeconds` | How far `timestamp` may be from now, 300 seconds by default. Setting it requires a timestamp |

```ts luna/lunas/payments.ts
const ok = verifyWebhook(body, req.headers.get("x-signature") ?? "", secret, {
  prefix: "sha256=",
  timestamp: req.headers.get("x-timestamp") ?? undefined,
});
```

A signed timestamp keeps an old request from being sent again later. An empty secret or an unknown encoding throws a `TypeError`, so check that the secret is set first.

## Run each delivery once

A sender that gets no answer in time sends the event again, so the same event can arrive twice. Keep each event's id in a table, and do nothing for an id you have seen.

```ts luna/lunas/shop.ts
import { defineLuna, t, table } from "luna";

export const Shop = defineLuna({
  name: "Shop",
  key: { id: t.string() },
  schema: { deliveries: table({ id: t.string(), at: t.timestamp() }, { primaryKey: ["id"] }) },
  handlers: (h) => ({
    paid: h({ args: { delivery: t.string(), amount: t.int() } }, (ctx, { delivery, amount }): void => {
      if (ctx.db.deliveries.get(delivery)) return;
      ctx.db.deliveries.insert({ id: delivery, at: ctx.now() });
      ctx.send(Shop, ctx.key).fulfil({ amount });
    }),
    fulfil: h({ args: { amount: t.int() } }, (ctx, { amount }) => {
      console.log(`fulfilling ${amount} for ${ctx.key.id}`);
    }),
  }),
});
```

The code between two `await`s runs with nothing else in between, and `paid` has no `await`. Two copies of the event cannot both pass the check. A handler that calls its own luna type spells out its return type, here `void`.

## Answer at once and work later

`paid` does no slow work. It records the delivery and sends a message, and both are kept together, so the work is never lost and the webhook answers in time. The message runs `fulfil` after the webhook has its answer.

Make `fulfil` a durable handler. A step's result is recorded once it finishes, so after a crash the run starts again and skips the steps already done.

```ts luna/lunas/shop.ts
fulfil: h({ args: { amount: t.int() }, durable: true }, async (ctx, { amount }) => {
  const order = JSON.stringify({ shop: ctx.key.id, amount });
  for (const url of ["https://mail.example.com/receipts", "https://ship.example.com/orders"]) {
    await ctx.step(url, async () => {
      const r = await fetch(url, { method: "POST", body: order });
      if (!r.ok) throw new Error(`${url} answered ${r.status}`);
    });
  }
}),
```

A step that throws is tried again, 3 times in all unless you set `attempts`. Steps, retries and backoff are in [Run durable work](/background/run-durable-work). Messages and their retries are in [Call another luna](/lunas/call-another-luna).

## Next steps

- [Process webhooks reliably](/recipes/process-webhooks-reliably) builds the whole flow as one app.
- [Check who is calling](/http/check-who-is-calling) checks callers that send a token instead of a signature.
- [Store secrets](/develop/store-secrets) covers how a secret reaches running lunas.
