How to receive webhooks in Node.js minimal receiver → production-ready processing
Start with a minimal “native” receiver, but don’t stop there.
In production, reliable webhook handling means verification, retries, idempotency, and backpressure — which is where Hooque simplifies everything.
Building for a specific provider? Browse provider webhook APIs.
TL;DR
- Treat “receive webhooks in Node.js” as an ops problem, not just a route handler.
- Verify the request before parsing/side effects (use a verifySignature(...) stub, then implement provider verification).
- Return 2xx quickly; move work to a worker/queue to avoid timeouts and retries.
- Assume retries and design idempotency (dedupe by event id + unique constraints).
- Log + store raw payloads for replayable debugging.
- If you need one workflow across many providers, centralize ingest + standardize consumption.
Deep dives: security, retries, queue migration.
Anti-patterns
- Doing business logic inline in the Node.js request handler.
- Parsing/transforming the body before verification (breaks signing inputs).
- Returning 2xx before authenticity is proven.
- Skipping idempotency (retries become double side effects).
If you’re triaging a live incident, use the debugging playbook .
Table of contents
Framework shortcuts
If you’re already using a framework, jump straight to the minimal framework receiver, then reuse the same production guidance and Hooque consumer loops.
Why it's hard in production
A route handler is the easy part. Supporting multiple senders means multiple security models, spikes, and retry semantics.
Verify authenticity + stop replays
Use a verifySignature(...) stub here, then implement real verification + replay defense for each provider.
Assume retries (duplicates are optional)
Treat every delivery as at-least-once and make side effects idempotent (DB constraints, dedupe keys).
Don’t do work in the request path
Ack fast, process async. Otherwise timeouts, deploys, and spikes turn into missed webhooks.
Debug with real payloads
Save the exact body + headers so you can replay deterministically after a fix.
Add monitoring + alerts early
Track delivered vs rejected, processing latency, queue depth, and error rates.
Iterate locally without losing events
Tunnels help, but durable capture + replay removes the “my laptop was asleep” problem.
Minimal standard-library receiver (Node.js)
This is a minimal starting point. Keep verifySignature(...) as a stub here, then implement provider-specific verification and replay defense in the
security guide
.
// Node 18+ (no framework)
// Run: node server.js
import http from "node:http";
function verifySignature(headers, body) {
// don't compromise on security
// TODO: implement provider-specific signature verification
}
function processData(body) {
// TODO: your business logic (DB writes, external API calls, etc.)
}
const server = http.createServer(async (req, res) => {
if (req.method !== "POST") return res.writeHead(405).end();
const chunks = [];
for await (const chunk of req) chunks.push(chunk);
const body = Buffer.concat(chunks);
verifySignature(req.headers, body);
// What happens if it fails or times out?
// Most providers retry -> duplicates unless you designed idempotency.
processData(body);
// IMPORTANT: ack fast; do not do real work inline.
res.writeHead(200, { "content-type": "text/plain" });
res.end("ok");
// TODO: enqueue / write to a queue / trigger async worker
setImmediate(() => console.log("received webhook bytes:", body.length));
});
server.listen(3000, () => console.log("listening on http://localhost:3000")); Hooque turns any webhook into a reliable queue.
Non-obvious scenario: you can’t expose a port
In real deployments, the hardest part is often “where does this endpoint run?” (NAT, corporate networks, locked-down environments, short-lived preview deployments). Hooque decouples inbound receiving from processing so your Node.js app doesn’t need to be the public receiver.
The easy path: receive with Hooque + consume forever
Hooque turns inbound webhooks into a durable queue. Your code becomes a run-forever worker that pulls or streams events and acks/nacks/rejects explicitly.
- No need to run a public webhook endpoint in every environment (especially for local dev).
- Durable capture + replay/inspection so “we missed the webhook” becomes debuggable.
- Explicit Ack / Nack / Reject lifecycle so retries are under your control.
- Backpressure and spike absorption: buffer now, process at your pace.
- One consumption pattern across many senders (even if their security/retry rules differ).
Flow
- Provider delivers → Hooque ingest endpoint
- Hooque persists payload immediately
- Your worker pulls (REST) or streams (SSE)
- Your worker ack/nack/rejects explicitly
Next steps
- Security: verification + replay defense
- Reliability: retries + idempotency
- Ops: metrics + alerting
Hooque REST polling loop (runs forever)
Polling is a good default when you want a simple worker loop. It also works in environments where long-lived connections are unreliable.
// Node 18+ (fetch built-in)
const NEXT_URL = process.env.HOOQUE_QUEUE_NEXT_URL ?? "https://app.hooque.io/queues/<consumerId>/next";
const TOKEN = process.env.HOOQUE_TOKEN ?? "hq_tok_replace_me";
const headers = { Authorization: `Bearer ${TOKEN}` };
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function main() {
while (true) {
const msg = await getNextMessage();
if (!msg) {
await sleep(1000);
continue;
}
try {
await processData(msg.payload, msg.meta);
await ack(msg);
} catch (err) {
await nack(msg, err);
}
}
}
async function getNextMessage() {
try {
const resp = await fetch(NEXT_URL, { headers });
if (resp.status === 204) return null;
if (!resp.ok) {
console.error("next() failed:", resp.status, await resp.text());
return null;
}
const meta = JSON.parse(resp.headers.get("X-Hooque-Meta") ?? "{}");
const contentType = (resp.headers.get("content-type") ?? "").toLowerCase();
const raw = await resp.text();
const payload = contentType.includes("json") ? JSON.parse(raw) : raw;
return { payload, meta };
} catch (err) {
console.error("Worker connection err:", err);
return null;
}
}
async function processData(payload, meta) {
// Example real-life task: run a script on webhook events.
console.log("event:", meta?.messageId ?? meta?.deliveryId);
}
async function ack(msg) {
if (msg.meta.ackUrl) {
fetch(msg.meta.ackUrl, { method: "POST", headers }).catch(e => console.error("ack err", e));
}
}
async function nack(msg, err) {
const reason = err instanceof Error ? err.message : String(err);
const url = msg.meta.nackUrl ?? msg.meta.rejectUrl;
if (url) {
fetch(url, {
method: "POST",
headers: { ...headers, "Content-Type": "application/json" },
body: JSON.stringify({ reason }),
}).catch(e => console.error("nack err", e));
}
}
main(); Hooque SSE stream consumer (runs forever)
SSE is great for low-latency processing: keep a connection open, process events as they arrive, and reconnect on disconnects.
// Node 18+ — SSE consumer (no extra packages)
const STREAM_URL = process.env.HOOQUE_QUEUE_STREAM_URL ?? "https://app.hooque.io/queues/<consumerId>/stream";
const TOKEN = process.env.HOOQUE_TOKEN ?? "hq_tok_replace_me";
const headers = { Authorization: `Bearer ${TOKEN}`, Accept: "text/event-stream" };
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function main() {
for await (const msg of getMessageStream()) {
try {
await processData(msg.payload, msg.meta);
await ack(msg);
} catch (err) {
await nack(msg, err);
}
}
}
async function* getMessageStream() {
while (true) {
try {
const resp = await fetch(STREAM_URL, { headers });
if (!resp.ok) throw new Error(`stream failed: ${resp.status} ${await resp.text()}`);
if (!resp.body) throw new Error("missing response body");
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let buf = "", event = null, dataLines = [];
while (true) {
const { value, done } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
while (true) {
const idx = buf.indexOf("\n");
if (idx < 0) break;
const line = buf.slice(0, idx).replace(/\r$/, "");
buf = buf.slice(idx + 1);
if (line.startsWith(":")) continue;
if (line === "") {
if (event === "message" && dataLines.length) {
try {
const rawMsg = JSON.parse(dataLines.join("\n"));
yield { payload: decodePayload(rawMsg), meta: rawMsg.meta ?? {} };
} catch { /* invalid json payload */ }
}
event = null;
dataLines = [];
continue;
}
if (line.startsWith("event:")) event = line.slice(6).trim();
if (line.startsWith("data:")) dataLines.push(line.slice(5).trimStart());
}
}
} catch (err) {
console.error("stream dropped:", err);
await sleep(2000);
}
}
}
function decodePayload(msg) {
let raw = msg.payload ?? "";
if (msg.encoding === "base64") {
raw = Buffer.from(raw, "base64").toString("utf8");
}
if ((msg.contentType ?? "").toLowerCase().includes("json")) return JSON.parse(raw);
return raw;
}
async function processData(payload, meta) {
// Example real-life task: run a script on webhook events.
console.log("event:", meta?.messageId ?? meta?.deliveryId);
}
async function ack(msg) {
if (msg.meta.ackUrl) {
fetch(msg.meta.ackUrl, { method: "POST", headers }).catch(e => console.error("ack err", e));
}
}
async function nack(msg, err) {
const reason = err instanceof Error ? err.message : String(err);
const url = msg.meta.nackUrl ?? msg.meta.rejectUrl;
if (url) {
fetch(url, {
method: "POST",
headers: { ...headers, "Content-Type": "application/json" },
body: JSON.stringify({ reason }),
}).catch(e => console.error("nack err", e));
}
}
main(); FAQ
Quick answers for the questions that come up right before you ship.
What status code should I return for webhooks in Node.js?
General: Usually return a fast 2xx after validating authenticity and basic schema. Timeouts and 5xx commonly trigger retries.
How Hooque helps: Hooque acknowledges ingest immediately and persists the payload. Your worker acks/nacks/rejects explicitly after processing.
Do I need signature verification in Node.js?
General: Yes, unless the sender is fully trusted and on a private network. A public endpoint without verification is easy to forge and easy to replay.
How Hooque helps: Hooque can verify at ingest for supported providers or using generic strategies. Either way, your worker receives a normalized meta object and can stay focused on processing.
Why do I see duplicate webhook events in Node.js?
General: Retries are normal: timeouts, transient network failures, and 5xx responses all produce duplicates. Design idempotency around event ids and side-effect boundaries.
How Hooque helps: Hooque makes delivery outcomes explicit (ack/nack/reject) and provides replay/inspection so you can fix issues without guessing what was received.
How do I test webhooks locally in Node.js?
General: You can use a tunnel, but local dev still breaks on sleep, VPNs, clock skew, and signature-byte mismatches.
How Hooque helps: With Hooque you can avoid inbound locally: receive events into a durable queue and pull/stream to your laptop, then replay from the UI after changes.
Should I use REST polling or SSE streaming for webhook processing?
General: Use REST polling for simple batch workers and environments without long-lived connections. Use SSE for low-latency “process as it arrives” flows.
How Hooque helps: Hooque supports both: `GET /next` for polling and `GET /stream` for streaming. Both include meta with ready-to-call ack/nack/reject URLs.
Start processing webhooks reliably
Create a webhook endpoint, receive events, then run your worker forever using REST polling or SSE streaming — with explicit ack/nack/reject control.
No credit card required