Webhook Receiver in Node.js: HMAC Signature Example
A Node.js webhook receiver that reads the raw body, checks the X-AyeWatch-Signature HMAC with crypto.timingSafeEqual, answers fast and skips repeated update_ids. Plain http and Express versions.
By AyeWatch Team5 min read
Short answer: A Node.js webhook receiver should read the raw request body, compute the HMAC-SHA256 of those exact bytes with your secret, and compare it with the signature header using crypto.timingSafeEqual before parsing JSON. For AyeWatch the header is X-AyeWatch-Signature with a sha256= prefix; answer 200 within 10 seconds and skip repeated update_ids.
Why the raw body matters
AyeWatch signs the exact bytes it sends: X-AyeWatch-Signature: sha256= followed by the hex HMAC-SHA256 of the request body, keyed with your webhook secret. If your code parses the JSON and serializes it again before hashing, the bytes can differ, for example in escaped characters or number formats, and a valid delivery fails the check.
So the order is fixed: collect the body as a Buffer, verify, then parse. The two versions below do that with no framework and with Express.
Plain Node.js, no dependencies
// server.js: Node.js 18 or later, no dependencies.
// Run: AYEWATCH_WEBHOOK_SECRET=your_secret node server.js
const http = require("node:http");
const crypto = require("node:crypto");
const SECRET = process.env.AYEWATCH_WEBHOOK_SECRET;
const MAX_BODY = 1024 * 1024;
const seen = new Set(); // use a database or Redis in production
function validSignature(raw, header) {
const expected = "sha256=" + crypto.createHmac("sha256", SECRET).update(raw).digest("hex");
const a = Buffer.from(expected);
const b = Buffer.from(header || "");
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
async function handle(update) {
// Save the alert or put it on a queue here. Keep it well under 10 seconds.
console.log(update.update_id, update.topic_name, update.headline);
}
http
.createServer((req, res) => {
if (req.method !== "POST" || req.url !== "/ayewatch") {
res.writeHead(404).end();
return;
}
const chunks = [];
let size = 0;
req.on("data", (chunk) => {
size += chunk.length;
if (size <= MAX_BODY) chunks.push(chunk);
});
req.on("end", async () => {
if (size > MAX_BODY) {
res.writeHead(413).end();
return;
}
const raw = Buffer.concat(chunks);
if (!validSignature(raw, req.headers["x-ayewatch-signature"])) {
res.writeHead(401).end();
return;
}
const update = JSON.parse(raw.toString("utf8"));
if (seen.has(update.update_id)) {
res.writeHead(200).end();
return;
}
try {
await handle(update);
seen.add(update.update_id);
res.writeHead(200).end();
} catch (err) {
console.error(err);
res.writeHead(500).end(); // AyeWatch retries with the same update_id
}
});
})
.listen(process.env.PORT || 3000);
crypto.timingSafeEqual throws when the two buffers differ in length, so the length check comes first. A comparison with === would work but leaks timing; the constant-time compare doesn't. The update_id is recorded and the 200 sent only after handle() finishes. If it throws, the 500 makes AyeWatch retry with the same update_id, so a failure costs a retry instead of an alert. Keep handle() short: for slow work, put the alert on a queue there and let a worker finish it.
Express
// npm install express
const express = require("express");
const crypto = require("node:crypto");
const app = express();
const SECRET = process.env.AYEWATCH_WEBHOOK_SECRET;
const seen = new Set(); // use a database or Redis in production
function validSignature(raw, header) {
const expected = "sha256=" + crypto.createHmac("sha256", SECRET).update(raw).digest("hex");
const a = Buffer.from(expected);
const b = Buffer.from(header || "");
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
// Raw body for this route only. Don't mount express.json() ahead of it.
app.post("/ayewatch", express.raw({ type: "application/json", limit: "1mb" }), async (req, res) => {
if (!Buffer.isBuffer(req.body) || !validSignature(req.body, req.get("X-AyeWatch-Signature"))) {
return res.sendStatus(401);
}
const update = JSON.parse(req.body.toString("utf8"));
if (seen.has(update.update_id)) return res.sendStatus(200);
try {
// Save the alert or put it on a queue here, then record it.
console.log(update.update_id, update.topic_name, update.headline);
seen.add(update.update_id);
res.sendStatus(200);
} catch (err) {
console.error(err);
res.sendStatus(500); // AyeWatch retries with the same update_id
}
});
app.listen(process.env.PORT || 3000);
If app.use(express.json()) runs before this route, it reads the body first and req.body becomes an object. The Buffer.isBuffer check turns that mistake into a clear 401 instead of a crash. Mount express.json() after the webhook route, or on the other routes only.
Mistakes that break verification
- Hashing parsed JSON. Hash the Buffer you received, not
JSON.stringify(req.body). - Dropping the prefix. The header value starts with
sha256=; compare the whole string or strip it from both sides. - A redirect in front of the receiver. AyeWatch does not follow 3xx responses and does not retry them. A trailing slash rule, an http to https upgrade or a www to apex redirect each make every delivery fail. Register the exact final URL.
- Slow handlers. Answer within 10 seconds. For slow work, put the alert on a queue, return 200 once it is queued, and let a worker finish it.
- A stale secret.
POST /api/v1/webhook/rotate-secretreplaces the secret at once, with no overlap, so update your receiver's environment straight after rotating.
Test it before going live
Sign a sample body with your secret and send it to the local server. This uses openssl and curl in a bash shell:
BODY='{"topic_id":1,"topic_name":"Test monitor","update_id":1,"headline":"Test","created_at":"2026-12-03T17:00:00Z"}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$AYEWATCH_WEBHOOK_SECRET" | sed 's/^.* //')
curl -i http://localhost:3000/ayewatch \
-H "Content-Type: application/json" \
-H "X-AyeWatch-Signature: sha256=$SIG" \
--data-raw "$BODY"
Expect 200. Change one character in BODY without re-signing and expect 401. Then register the public HTTPS URL with PUT /api/v1/webhook or in Notification settings, Webhook. The account holds one webhook URL, and the owner gets an email whenever it changes.
What this receiver won't handle
- Restarts and several instances. The in-memory
Setforgets on restart and isn't shared. Keep update IDs in Postgres or Redis, as in webhook idempotency. - Replays. Deliveries carry no timestamp header, so replay protection is the update_id dedupe.
- Order. Deliveries can arrive out of order. Sort by
created_at. - Unknown fields. Payloads can gain fields. Read the ones you need and ignore the rest.
Ship the receiver
- Copy the plain http or Express version and set AYEWATCH_WEBHOOK_SECRET.
- Run the openssl test locally and confirm 200 for a signed body and 401 for a changed one.
- Deploy behind HTTPS at a URL that answers without redirects.
- Register it with PUT /api/v1/webhook, or paste it in Notification settings.
- Replace the in-memory Set with a database claim before you run more than one instance.
| Response | When to send it | What AyeWatch does |
|---|---|---|
| 200 | Signature valid, work queued or already done | Marks the delivery done |
| 401 | Signature invalid | Retries; fix the secret |
| 413 | Body over your size limit | Retries |
| 500 | Your work failed and should run again | Retries with backoff, up to 10 attempts |
| 3xx | Never | Fails the delivery at once, no retry |
Start a monitor in under a minute
Describe a topic or paste a URL. Cancel before the trial ends and you pay nothing.
Try it free for 7 daysThe bottom line
Run the openssl test until you get a 200 and a 401, then deploy. Before a second instance goes up, move the seen set into your database.
FAQ
How do I verify an HMAC webhook signature in Node.js?
Compute crypto.createHmac('sha256', secret).update(rawBody).digest('hex'), add the sha256= prefix, check the lengths match and compare with crypto.timingSafeEqual.
Why does my Express webhook signature never match?
Usually express.json() parsed the body before your route. Use express.raw on the webhook route and hash the Buffer it gives you.
Why use crypto.timingSafeEqual instead of ===?
It takes the same time whatever the input, so an attacker can't learn the signature from response timings. It throws on different lengths, so check them first.
How fast must the receiver answer?
Within 10 seconds, with a 2xx status. Answer first and do slow work afterwards or in a queue.
Do webhooks cost extra on AyeWatch?
No. Webhooks come with paid plans and the 7-day trial. Credits are spent on checks, not deliveries.