Skip to content
jshacks.dev
APIs

Implement webhooks with signature headers

Implement webhooks with a signature header that signs the timestamp and the body together, so receivers can reject tampered and replayed requests.

2 min read
Summarize in AI

A signature over the body alone proves who sent it, but not when. An attacker who captures a valid request can replay it later. Signing a timestamp with the body closes that gap.

signed-webhook.jsJavaScript
import { createHmac, timingSafeEqual } from 'node:crypto';

const secret = 'whsec_demo';

function sign(body, timestamp) {
  const mac = createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex');
  return `t=${timestamp},v1=${mac}`;
}

function verify(header, body, now, toleranceSec = 300) {
  const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')));
  if (Math.abs(now - Number(parts.t)) > toleranceSec) return false;
  const expected = createHmac('sha256', secret).update(`${parts.t}.${body}`).digest();
  const received = Buffer.from(parts.v1, 'hex');
  return received.length === expected.length && timingSafeEqual(received, expected);
}

const body = '{"event":"paid"}';
const header = sign(body, 1_700_000_000);

console.log(verify(header, body, 1_700_000_100));
console.log(verify(header, body, 1_700_001_000));
console.log(verify(header, '{"event":"refund"}', 1_700_000_100));
Text
true
false
false

The first check passes: the signature is valid and the request is 100 seconds old. The second is rejected as too old, even though the signature is correct, and the third fails because the body changed.

The header format, t=...,v1=..., is the one Stripe uses, and the v1 label leaves room for a new scheme later. Send the header as X-Signature or a name of your choosing, and give receivers a way to rotate the secret.

Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
APIs

Accept multipart upload in Node.js

Accept a multipart file upload in Node.js by wrapping the incoming request in a Request object and reading it with formData.

1 min read
Performance

Reduce JSON size by removing nulls

Drop null and undefined fields from an API payload with a JSON.stringify replacer, shrinking responses, and check clients treat a missing key like null.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.