API · v1 · stable
CODEMETA OSDeveloper Center
EN
Open console
Tutorial

Secure a webhook receiver

Reading time · 8 minUpdated · 1 May 2026

Webhooks are incoming HTTP requests. If your receiver does not check authenticity, anyone can forge events. This tutorial shows the minimum you have to do.

What Codemeta OS sends

Every webhook request contains:

  • Body: JSON payload of the event.
  • Header X-Webhook-Signature: HMAC-SHA256 over the raw request body.
  • Header Content-Type: application/json.

You receive the HMAC key when you create the webhook subscription. Store it as a secret – ideally in your stack’s vault.

  1. Read the raw body. Important: before parsing. As soon as your framework parses the body as JSON and serializes it again, the whitespace layout may differ and the signature check fails.

    In Express: express.raw({ type: 'application/json' }) as middleware before the route.

  2. Compute and compare the signature.

    import crypto from 'node:crypto';
    
    function verifyWebhook(rawBody: Buffer, signature: string, secret: string) {
      const expected = crypto
        .createHmac('sha256', secret)
        .update(rawBody)
        .digest('hex');
      // timingSafeEqual protects against timing attacks
      return crypto.timingSafeEqual(
        Buffer.from(expected, 'hex'),
        Buffer.from(signature, 'hex'),
      );
    }
  3. Process the event idempotently. Codemeta OS retries failed deliveries. So treat every event as something you may receive more than once. Store the event.id in your DB and skip events you have already seen.

    if (await db.events.has(event.id)) return res.status(200).end();
    await processEvent(event);
    await db.events.add(event.id);
  4. Respond quickly with 2xx. Codemeta OS waits a few seconds per delivery for your response. Do not do expensive work synchronously in the webhook handler – accept the event, respond with 204 No Content, and process it in a background job.

Search