# Verify webhook signatures in Node.js (/docs/guides/verify-webhook-signatures)

A webhook URL is public: anyone who finds it can post to it. Verifying the signature proves a
request came from coss.com and that its body wasn't changed, and checking its age stops someone
from replaying a request they captured. Do both before you trust anything in the body.

## How coss.com signs webhooks [#how-cosscom-signs-webhooks]

Requests follow [Standard Webhooks](https://www.standardwebhooks.com) and carry three headers:

| Header              | Value                                                                         |
| ------------------- | ----------------------------------------------------------------------------- |
| `webhook-id`        | The event's id, the same on every retry                                       |
| `webhook-timestamp` | When it was sent, in Unix seconds                                             |
| `webhook-signature` | `v1,<base64 HMAC-SHA256>`, space-separated when there is more than one secret |

The signature is an HMAC-SHA256 of `<webhook-id>.<webhook-timestamp>.<raw body>`, keyed with the
endpoint's `whsec_…` signing secret. You don't need to compute it yourself: `verifyWebhook` from the
`coss` package checks the signature and the timestamp, and returns the parsed event. Get the secret
when you [create the endpoint](/docs/webhooks) (it's returned once) or from the dashboard.

## Verify webhooks in a Next.js route handler [#verify-webhooks-in-a-nextjs-route-handler]

Read the body with `request.text()`. Parsing it as JSON and serializing it again changes the bytes,
and the signature no longer matches.

```ts twoslash title="app/webhooks/coss/route.ts"
import { verifyWebhook, WebhookVerificationError } from "coss";

export async function POST(request: Request) {
  try {
    const event = await verifyWebhook(
      await request.text(),
      request.headers,
      process.env.COSS_WEBHOOK_SECRET!,
    );

    if (event.type === "email.bounced") {
      console.log(event.data.recipient, event.data.bounce?.type);
    }
    return new Response("ok");
  } catch (error) {
    if (error instanceof WebhookVerificationError) {
      return new Response("invalid signature", { status: 400 });
    }
    throw error;
  }
}
```

`verifyWebhook` is the one SDK function that throws instead of returning `{ data, error }`: a failed
check must not be ignorable. The event is typed by its `type`, so `event.data` narrows as you check it.

## Verify webhooks in Express [#verify-webhooks-in-express]

Express parses JSON for you, which loses the raw body. Mount `express.raw()` on the webhook route
so `req.body` stays a `Buffer`, and register it before any global `express.json()`:

```ts twoslash title="server.ts"
type Middleware = { readonly middleware: true };
type Req = { body: Buffer; headers: Record<string, string | string[] | undefined> };
type Res = { status(code: number): Res; send(body: string): void };
type App = {
  post(path: string, middleware: Middleware, handler: (req: Req, res: Res) => Promise<void>): void;
  listen(port: number): void;
};
declare const express: { (): App; raw(options: { type: string }): Middleware };
// ---cut---
import { verifyWebhook, WebhookVerificationError } from "coss";

const app = express();

app.post("/webhooks/coss", express.raw({ type: "application/json" }), async (req, res) => {
  try {
    const event = await verifyWebhook(
      req.body.toString("utf8"),
      req.headers, // a Node-style header record works as well as Headers
      process.env.COSS_WEBHOOK_SECRET!,
    );
    console.log(event.type, event.id);
    res.status(200).send("ok");
  } catch (error) {
    if (error instanceof WebhookVerificationError) {
      res.status(400).send("invalid signature");
      return;
    }
    throw error;
  }
});

app.listen(3000);
```

## The timestamp tolerance window [#the-timestamp-tolerance-window]

Requests older than 5 minutes, or from a clock more than 5 minutes off, fail verification. Keep your
server's clock synced. To change the window, pass `{ toleranceSeconds: 600 }` as the fourth argument.

## Rotate the signing secret without downtime [#rotate-the-signing-secret-without-downtime]

[Rolling a secret](/docs/webhooks#rolling-the-secret) starts a grace period (a day by default, up to
a week) in which each request carries two signatures, one per secret. `verifyWebhook` accepts a
request when any signature matches, so your handler keeps working with the old secret until you
deploy the new one.

## Handle retries and duplicates [#handle-retries-and-duplicates]

- Respond with a `2xx` status within 10 seconds. Anything else, or no answer, is retried 7 times
  over about 28 hours (see [delivery and retries](/docs/webhooks#delivery-and-retries)).
- Do slow work after responding: store the event or put it on a queue, then answer.
- The same event can arrive more than once. Deduplicate by `event.id`, which equals the
  `webhook-id` header.
- Events can arrive out of order: sort by `data.occurred_at`.

```ts twoslash title="app/webhooks/coss/route.ts"
import type { WebhookEvent } from "coss";
/** Stores the id; resolves false when it was already stored. */
declare function markProcessed(eventId: string): Promise<boolean>;
declare function enqueue(event: WebhookEvent): Promise<void>;
// ---cut---
import { verifyWebhook } from "coss";

export async function POST(request: Request) {
  const event = await verifyWebhook(await request.text(), request.headers, process.env.COSS_WEBHOOK_SECRET!);
  if (await markProcessed(event.id)) await enqueue(event);
  return new Response("ok");
}
```

## Test webhooks locally [#test-webhooks-locally]

coss.com can't reach `localhost`. Run [`coss listen`](/docs/cli#receive-webhooks-locally) in a
sandbox environment: it forwards each event to your server, signed with a secret it writes to your
project's env file as `COSS_WEBHOOK_SECRET`, so the handler verifies exactly as in production. Then
send a sample event of any type with [`coss trigger`](/docs/cli#trigger-test-events):

```sh
# terminal 1
coss listen --forward-to localhost:3000/webhooks/coss
# terminal 2
coss trigger email.bounced
```

Test events are signed and delivered like real ones, in sandbox environments only. Their ids are
made up: pass real ones with `--data` or `-F` if your handler looks them up.

## Verify Hooks messages the same way [#verify-hooks-messages-the-same-way]

If you send webhooks to your own customers with [Hooks](/docs/hooks), their endpoints receive the
same headers and verify with the same `verifyWebhook`, typed with your own payload. Share
[Receiving messages](/docs/hooks/receiving) with them.

## Next steps [#next-steps]

- [Webhooks](/docs/webhooks): every event type, delivery logs and retrying failed deliveries.
- [Verifying webhooks](/docs/sdk/webhooks): the `verifyWebhook` reference.
- [Receive email in your app](/docs/guides/receive-email): handle `email.received`.
