Skip to content
jshacks.dev
Node.js

Build a Webhook Relay With Node.js

Build a webhook relay in Node.js that verifies HMAC signatures on the raw body, replies fast, and forwards events to targets with retries and backoff.

8 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the Node.js, NGINX, Postman and Swagger logos.

A webhook relay sits between a service that sends events and the systems that need them. A payment provider posts to one URL, and your relay verifies the request, answers quickly, and forwards the event to a billing service, a chat notifier and a staging copy of your app. Teams build one when the sender allows a single endpoint, when a target is sometimes down, or when they want a place to inspect traffic. This post builds a small relay on Node.js 26 'Lithium', the LTS line since 2026-10-28, using only built-in modules: node:http for the server, node:crypto for signatures and the global fetch for delivery. The same code runs on the Node.js 24 and 22 maintenance lines.

The three jobs of a relay

A relay that works in production does three things in a fixed order, and getting the order wrong is where most bugs come from.

  • Verify the signature against the exact bytes that were sent, and reject the request if it does not match.

  • Acknowledge with a fast 202, before any forwarding happens, because senders time out and then retry, which creates duplicates.

  • Deliver to each target independently, with retries and backoff, so one slow target never blocks the others.

The first job is the subtle one. Providers sign the raw request body. If you parse the JSON and serialize it again, whitespace and key order can change and the signature no longer matches, even for a genuine request. So the server collects the body as bytes, verifies, and only then parses.

Verifying a signature

Most providers send a header such as X-Signature: sha256=<hex> where the hex string is an HMAC-SHA-256 of the body under a shared secret. The exact header name and format vary, so read your provider's documentation and adjust. The comparison must be constant-time, which is what timingSafeEqual in the crypto module is for.

verify.jsJavaScript
import { createHmac, timingSafeEqual } from "node:crypto";

export function sign(rawBody, secret) {
  return "sha256=" + createHmac("sha256", secret).update(rawBody).digest("hex");
}

export function verifySignature(rawBody, header, secret) {
  if (typeof header !== "string") return false;
  const expected = Buffer.from(sign(rawBody, secret));
  const given = Buffer.from(header);
  return expected.length === given.length && timingSafeEqual(expected, given);
}

const secret = "whsec_test";
const body = Buffer.from('{"event":"paid","id":42}');
const header = sign(body, secret);

console.log(verifySignature(body, header, secret));
console.log(verifySignature(Buffer.from('{"event":"paid","id":43}'), header, secret));
console.log(verifySignature(body, undefined, secret));
console.log(verifySignature(body, "sha256=abc", secret));

The first call verifies a body against a signature made from the same bytes. The second changes one digit in the body, so the digest differs. The third has no header at all, and the fourth has a header of the wrong length, which the length check rejects before timingSafeEqual can throw.

Text
true
false
false
false

Two habits are worth keeping. Never log the secret or the full computed signature, since a log line is a place secrets leak. And if the provider includes a timestamp in the signed payload, reject requests older than a few minutes, which blocks replay of a captured request.

Delivering with retries and backoff

Forwarding is a network call to a system you do not control, so it fails. A target returns 503 during a deploy, a connection resets, a DNS lookup times out. The standard answer is retry with exponential backoff: wait a base delay, then double it on each attempt. Retry on network errors and on 5xx and 429 responses. Do not retry other 4xx statuses, because those mean the target understood the request and refused it, and sending it again will not change the answer.

The delivery function takes fetch and sleep as parameters. In production you pass the real ones. In a check you pass fakes, so the test is instant and the output is exact.

deliver.jsJavaScript
export async function deliver(url, body, opts = {}) {
  const {
    fetchFn = fetch,
    sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
    retries = 3,
    baseMs = 100,
  } = opts;

  for (let attempt = 0; attempt <= retries; attempt++) {
    try {
      const res = await fetchFn(url, {
        method: "POST",
        headers: { "content-type": "application/json" },
        body,
        signal: AbortSignal.timeout(5000),
      });
      if (res.ok) return { ok: true, attempts: attempt + 1 };
      const retryable = res.status >= 500 || res.status === 429;
      if (!retryable) return { ok: false, attempts: attempt + 1, status: res.status };
      console.log(`attempt ${attempt + 1} got ${res.status}`);
    } catch (err) {
      console.log(`attempt ${attempt + 1} threw ${err.name}`);
    }
    if (attempt < retries) {
      const wait = baseMs * 2 ** attempt;
      console.log(`waiting ${wait} ms`);
      await sleep(wait);
    }
  }
  return { ok: false, attempts: retries + 1 };
}

const responses = [{ ok: false, status: 503 }, { ok: false, status: 503 }, { ok: true, status: 200 }];
const fakeFetch = async () => responses.shift();

console.log(await deliver("https://target.test/hook", "{}", { fetchFn: fakeFetch, sleep: async () => {} }));
console.log(await deliver("https://target.test/hook", "{}", {
  fetchFn: async () => ({ ok: false, status: 400 }),
  sleep: async () => {},
}));

The fake target fails twice with 503 and then succeeds. The waits are 100 ms and 200 ms, because the delay doubles per attempt, and the third attempt returns the success result. The second call gets a 400, which is not retryable, so it stops after one attempt and reports the status. Node.js prints a plain object on one line when it is short enough.

Text
attempt 1 got 503
waiting 100 ms
attempt 2 got 503
waiting 200 ms
{ ok: true, attempts: 3 }
{ ok: false, attempts: 1, status: 400 }

AbortSignal.timeout(5000) bounds each attempt, so a target that accepts the connection and never answers cannot hold a delivery forever. In production add random jitter to the wait, for example a random fraction of the delay, so that many failed deliveries do not all retry at the same instant.

The server

The server reads the raw body with a size limit, verifies the signature, answers, and then delivers in the background. The path decides the route, so POST /hooks/payments could fan out to different targets than POST /hooks/orders. A small table keeps that mapping in one place.

server.jsJavaScript
import { createServer } from "node:http";
import { verifySignature } from "./verify.js";
import { deliver } from "./deliver.js";

const SECRET = process.env.RELAY_SECRET;
const MAX_BYTES = 1_000_000;
const routes = {
  "/hooks/payments": ["https://billing.internal/hook", "https://notify.internal/hook"],
};

function readBody(req) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    let size = 0;
    req.on("data", (chunk) => {
      size += chunk.length;
      if (size > MAX_BYTES) {
        reject(new Error("too large"));
        req.destroy();
        return;
      }
      chunks.push(chunk);
    });
    req.on("end", () => resolve(Buffer.concat(chunks)));
    req.on("error", reject);
  });
}

const server = createServer(async (req, res) => {
  const targets = routes[req.url];
  if (req.method !== "POST" || !targets) {
    res.writeHead(404).end();
    return;
  }
  let body;
  try {
    body = await readBody(req);
  } catch {
    res.writeHead(413).end();
    return;
  }
  if (!verifySignature(body, req.headers["x-signature"], SECRET)) {
    res.writeHead(401).end();
    return;
  }
  res.writeHead(202).end();
  for (const url of targets) {
    deliver(url, body).then((r) => console.log(url, r.ok ? "delivered" : "gave up"));
  }
});

server.listen(3000, () => console.log("relay listening on 3000"));

Starting it with RELAY_SECRET=whsec_test node server.js prints one line.

Text
relay listening on 3000

Posting the body {"event":"paid"} with a valid signature header returns 202 immediately, and posting the same body with a wrong header returns 401. Checked with curl -s -o /dev/null -w "%{http_code}\n", the two requests print:

Text
202
401

The deliveries then run after the response is sent. Each deliver call is independent, so a slow billing service does not delay the notifier. Note that the body passed to deliver is the original buffer, which means targets receive exactly the bytes the provider sent and can verify their own copy of the signature if they share the secret.

Making it safe to run

The relay as written keeps pending deliveries in memory. If the process restarts while a target is down, those events are gone. That is acceptable for notifications and not for payments. The next step is to write each accepted event to disk or a queue before acknowledging, and let a worker drain the queue. Until then, keep the retry budget short enough that a deploy does not drop much, and handle SIGTERM by calling server.close() and waiting for in-flight deliveries.

Idempotency matters on both sides. Providers retry, so the same event can arrive twice; most include an event id, and a relay that stores recent ids can drop duplicates before forwarding. Targets should still be idempotent, because the relay's own retries can duplicate a delivery whose response was lost.

Finally, put the relay behind TLS and rate limiting at the proxy, and keep the secret in the environment, not in the repository.

Where this relay stops

This design is a good fit for one process, a handful of routes and events you can afford to lose in a crash. It has no persistence, no dead-letter store for deliveries that exhaust their retries, and no per-target secrets. A single shared secret means every sender uses the same key, so a leak from one provider affects all. If you need guaranteed delivery, replay from a dashboard or many tenants, a durable queue with its own worker, or a hosted webhook service, is the right tool. The verify and deliver modules are small enough to carry over unchanged.

Operating the relay

A few operational habits keep a relay from becoming the thing that wakes you at night. Log one line per delivery outcome with the route, the target host and the attempt count, and never log bodies, since webhook payloads often hold personal data. Expose a health endpoint that answers without touching targets, so a load balancer can tell the process is alive. Keep a per-target timeout shorter than the sender's own timeout budget, because the relay should already have answered before the sender gives up.

The files above include small check lines at the bottom of verify.js and deliver.js so the output can be shown. In a real project, move those lines into a separate check file, otherwise importing the module from the server would run them.

Plan for the day a target is down for an hour. With the in-memory retry shown here, a delivery gives up after four attempts, which spans well under a second of waiting. That is right for transient glitches and wrong for an outage. The fix is a second tier: after the quick retries fail, write the event to a file or table with a next-attempt time, and let a timer pick it up later with a longer delay. Cap the total age, for example a day, and alert a person when events expire.

Finally, test the failure paths on purpose. Point a route at a port where nothing listens, at a server that returns 500 and at one that never replies, and confirm that the relay still answers the sender with 202 and that the other targets still receive the event.

Also inAPIs
Share

Keep reading

Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, RabbitMQ, Apache Kafka, Redis and npm logos.
Node.js

What Is Node.js, and What Is It Good At?

Node.js runs JavaScript outside the browser on the V8 engine. Learn what it is, how its event loop works, where it shines, and where another tool fits better.

6 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.