Verify webhook signatures in Node.js

Check the signature and age of every coss.com webhook in a Next.js route handler or Express, handle retries and duplicates, and test locally.

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

Requests follow Standard Webhooks and carry three headers:

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 (it's returned once) or from the dashboard.

Verify webhooks in a Next.js 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.

app/webhooks/coss/route.ts
import { ,  } from "coss";

export async function (: ) {
  try {
    const  = await (
      await .(),
      .,
      ..!,
    );

    if (. === "email.bounced") {
      .(.., ..?.);
    }
    return new ("ok");
  } catch () {
    if ( instanceof ) {
      return new ("invalid signature", { : 400 });
    }
    throw ;
  }
}

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

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():

server.ts
import { ,  } from "coss";

const  = ();

.("/webhooks/coss", .({ : "application/json" }), async (, ) => {
  try {
    const  = await (
      ..("utf8"),
      ., // a Node-style header record works as well as Headers
      ..!,
    );
    .(., .);
    .(200).("ok");
  } catch () {
    if ( instanceof ) {
      .(400).("invalid signature");
      return;
    }
    throw ;
  }
});

.(3000);

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

Rolling a 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

  • 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).
  • 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.
app/webhooks/coss/route.ts
import {  } from "coss";

export async function (: ) {
  const  = await (await .(), ., ..!);
  if (await (.)) await ();
  return new ("ok");
}

Test webhooks locally

coss.com can't reach localhost. Run coss listen 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:

# 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

If you send webhooks to your own customers with Hooks, their endpoints receive the same headers and verify with the same verifyWebhook, typed with your own payload. Share Receiving messages with them.

Next steps

Last updated