Guides
How to Build a Secure Webhook Receiver in Node.js
A complete, runnable Express receiver for messaging status webhooks, with installation, environment setup, local testing with curl, troubleshooting and a production checklist.
- Author
- By TXTPro Editorial Team
- Published
- Reading time
- 12 min read
What you will build
A single-file Express server with one route, POST /webhooks/messaging, that accepts delivery and interaction events for SMS, RCS, WhatsApp or voice. It authenticates each request, validates it, ignores duplicates, queues the event and processes it in the background.
Prerequisites and installation
You need Node.js 20.6 or later (for the built-in --env-file flag) and npm. Create a project and install Express:
mkdir webhook-receiver && cd webhook-receiver
npm init -y
npm install express
# Create .env.example and server.mjs as shown below, then:
cp .env.example .env # replace the placeholder values
node --env-file=.env server.mjsEnvironment configuration
Configuration comes from environment variables so that no secret is ever written in code. Create .env.example with placeholders and copy it to .env with real values:
# .env.example: copy to .env, fill in, and never commit .env.
# Generate a secret with: openssl rand -hex 32
WEBHOOK_SIGNING_SECRET=replace-with-a-random-64-character-hex-string
# Example header name for local testing only. Use the name in your integration documentation.
WEBHOOK_SIGNATURE_HEADER=X-Webhook-Signature
PORT=3000Add .env to .gitignore. In production, set the same variables through your hosting platform or secrets manager instead of a file.
Complete Express webhook receiver
Save this as server.mjs. The .mjs extension lets Node.js use import syntax without changing package.json.
// server.mjs: generic Express receiver for messaging status webhooks.
// Requires Node.js 20+ and: npm install express
//
// ASSUMPTIONS (generic HMAC sample, not a confirmed TXTPro signing contract):
// 1. The sender signs the exact raw request body with HMAC-SHA256 and a shared secret.
// 2. The hex-encoded signature arrives in the header named by WEBHOOK_SIGNATURE_HEADER.
// 3. Each request carries one JSON event with the fields validated below.
// Replace these with the contract in your TXTPro integration documentation.
import crypto from 'node:crypto';
import express from 'express';
const SECRET = process.env.WEBHOOK_SIGNING_SECRET;
const SIGNATURE_HEADER = process.env.WEBHOOK_SIGNATURE_HEADER;
const PORT = Number(process.env.PORT) || 3000;
if (!SECRET || !SIGNATURE_HEADER) {
// Fail closed: refuse to start rather than accept unauthenticated callbacks.
console.error('Missing WEBHOOK_SIGNING_SECRET or WEBHOOK_SIGNATURE_HEADER. Refusing to start.');
process.exit(1);
}
const CHANNELS = new Set(['sms', 'rcs', 'whatsapp', 'voice']);
const FINAL_STATUSES = new Set(['DELIVERED', 'FAILED', 'REJECTED', 'EXPIRED', 'UNDELIVERED']);
function verifySignature(rawBody, received) {
if (typeof received !== 'string' || received.length === 0) return false;
const expected = crypto.createHmac('sha256', SECRET).update(rawBody).digest('hex');
const a = Buffer.from(expected, 'utf8');
const b = Buffer.from(received.trim(), 'utf8');
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
const isText = (value, max) => typeof value === 'string' && value.length > 0 && value.length <= max;
function validateEvent(body) {
if (typeof body !== 'object' || body === null || Array.isArray(body)) return null;
const { event_id, event_type, message_id, channel, status, timestamp } = body;
if (!isText(event_id, 128) || !isText(event_type, 64) || !isText(message_id, 128)) return null;
if (!CHANNELS.has(channel) || !isText(status, 32) || !isText(timestamp, 40)) return null;
if (Number.isNaN(Date.parse(timestamp))) return null;
return { event_id, event_type, message_id, channel, status: status.toUpperCase(), timestamp };
}
// In-memory stand-ins so the example runs as-is. In production use a database table
// with a unique key on event_id, and a durable queue (for example Redis, SQS or RabbitMQ).
const processedEventIds = new Set();
const queue = [];
const messages = new Map(); // provider message_id -> { status, statusAt }
const app = express();
app.disable('x-powered-by');
app.post('/webhooks/messaging', express.raw({ type: 'application/json', limit: '64kb' }), (req, res) => {
if (!req.is('application/json')) return res.status(415).json({ error: 'unsupported_media_type' });
const raw = req.body;
if (!Buffer.isBuffer(raw) || raw.length === 0) return res.status(400).json({ error: 'empty_body' });
if (!verifySignature(raw, req.get(SIGNATURE_HEADER))) return res.status(401).json({ error: 'invalid_signature' });
let body;
try {
body = JSON.parse(raw.toString('utf8'));
} catch {
return res.status(400).json({ error: 'invalid_json' });
}
const event = validateEvent(body);
if (!event) return res.status(422).json({ error: 'invalid_payload' });
if (processedEventIds.has(event.event_id)) return res.status(200).json({ received: true, duplicate: true });
processedEventIds.add(event.event_id);
queue.push(event);
// Log identifiers only: never phone numbers, message text, OTPs or secrets.
console.info('webhook accepted', { event_id: event.event_id, channel: event.channel, status: event.status });
return res.status(200).json({ received: true });
});
async function findMessageByProviderId(messageId) {
return messages.get(messageId) ?? null; // replace with a database lookup
}
async function updateMessageStatus(record, status, at) {
record.status = status; // replace with a database update
record.statusAt = at;
}
async function processEvent(event) {
const record = await findMessageByProviderId(event.message_id);
if (!record) {
console.warn('unknown message_id', { event_id: event.event_id });
return;
}
// Events can arrive out of order: never move a final status back to an interim one.
if (FINAL_STATUSES.has(record.status) && !FINAL_STATUSES.has(event.status)) return;
if (record.statusAt && Date.parse(record.statusAt) > Date.parse(event.timestamp)) return;
await updateMessageStatus(record, event.status, event.timestamp);
}
async function runWorker() {
for (;;) {
const event = queue.shift();
if (!event) {
await new Promise((resolve) => setTimeout(resolve, 200));
continue;
}
try {
await processEvent(event);
} catch (err) {
console.error('processing failed', { event_id: event.event_id, error: err.message });
// Move the event to a dead-letter store for review and retry.
}
}
}
app.use((err, req, res, next) => {
if (err.type === 'entity.too.large') return res.status(413).json({ error: 'payload_too_large' });
console.error('unhandled error', { message: err.message });
return res.status(500).json({ error: 'internal_error' });
});
runWorker();
app.listen(PORT, () => console.info(`Webhook receiver listening on port ${PORT}`));
How the receiver works
- Fail closed. If either environment variable is missing, the process logs an error and exits before listening.
- Raw body.
express.raw()is applied only to the webhook route, with a 64 KB limit, so the body arrives as a Buffer. - Signature check. An HMAC-SHA256 of the raw bytes is compared with the received header using
crypto.timingSafeEqual. - Parsing and validation. The body is parsed only after it is authenticated, then checked for required fields, allowed channels and a valid timestamp.
- Deduplication. An event ID that has been seen before is acknowledged with
duplicate: trueand not processed again. - Queue and acknowledge. New events are queued and the request is answered with 200 straight away.
- Background processing. A worker loop maps
message_idto your record and updates its status, refusing to move a final status back to an interim one. - Error handling. Oversized bodies return 413; unexpected errors return 500 without leaking details.
| Code | When | Effect |
|---|---|---|
| 200 | Event verified and queued, or a duplicate of an event already received | The sender should stop retrying |
| 400 | Empty body or invalid JSON | Permanent; the request needs fixing |
| 401 | Missing or invalid signature | Rejects unauthenticated callbacks |
| 413 | Body larger than 64 KB | Protects memory and workers |
| 415 | Content type is not application/json | Rejects unexpected formats |
| 422 | Valid JSON that fails schema validation | Permanent; the payload does not match |
| 500 | Unexpected server error | May trigger a retry where retries are supported |
Testing the receiver locally
Start the server with node --env-file=.env server.mjs; it prints “Webhook receiver listening on port 3000”. In another terminal, sign the illustrative payload with openssl and send it with curl:
# In a second terminal, load the same .env values first:
set -a; source .env; set +a
BODY='{"event_id":"evt_example_001","event_type":"message.delivered","message_id":"msg_example_123","channel":"sms","status":"DELIVERED","timestamp":"2026-11-08T10:30:00Z"}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$WEBHOOK_SIGNING_SECRET" | sed 's/^.*= //')
# Signed request: expect 200 {"received":true}
curl -i -w '
' -X POST http://localhost:3000/webhooks/messaging \
-H "Content-Type: application/json" -H "$WEBHOOK_SIGNATURE_HEADER: $SIG" --data "$BODY"
# Same request again: expect 200 {"received":true,"duplicate":true}
# Wrong signature: expect 401
curl -i -w '
' -X POST http://localhost:3000/webhooks/messaging \
-H "Content-Type: application/json" -H "$WEBHOOK_SIGNATURE_HEADER: bad" --data "$BODY"The server log shows “unknown message_id” for the test event because the in-memory message store starts empty, which is expected. To confirm the receiver fails closed, start it without the --env-file flag: it exits with “Refusing to start”.
To test from a real sender before deployment, expose the local port through an HTTPS tunnelling tool, and use test credentials only.
Moving the example to production
- Replace the in-memory
Set, array andMapwith a database (unique key onevent_id) and a durable queue, so state survives restarts and is shared between instances. - Run the worker as a separate process consuming the queue, and add retries with backoff and a dead-letter queue.
- Serve the app behind HTTPS (for example a load balancer or reverse proxy) and keep the Node.js process on a private network.
- Replace the assumed signature scheme with the one in your TXTPro integration documentation.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Every request returns 401 | A global express.json() parsed the body before the route | Mount express.json() only on other routes, or after the webhook route |
| Every request returns 401 in tests only | The test signs a different string from the one sent | Sign and send the exact same bytes; avoid re-serialising JSON |
| 415 responses | The sender’s Content-Type is not application/json | Confirm the content type in your integration documentation |
| Process exits immediately | Environment variables were not loaded | Use --env-file=.env (Node.js 20.6+) or set the variables in your host |
| Duplicates processed twice after a restart | In-memory deduplication was reset | Store event IDs in a database |
Production security checklist
- Secrets only in environment variables or a secrets manager;
.envnever committed - Receiver refuses to start without authentication configuration
- Signature verified over the raw body with
timingSafeEqual - Body size limit, content-type check and gateway rate limiting
- Event ID deduplication in durable storage
- Identifiers-only logging: no phone numbers, message text, OTPs or secrets
- HTTPS in front of the app, with monitoring and alerting on 4xx/5xx rates
Background on each control is in the webhook security guide. Prefer Python? The Python FastAPI webhook guide implements the same receiver.
Frequently asked questions
Why does the webhook route use express.raw instead of express.json?
Signature verification must use the exact bytes received. express.json parses and discards the original body, so the route reads the raw Buffer, verifies it, and only then parses the JSON.
Is this Node.js example compatible with TXTPro production webhooks?
Not directly. It uses a generic HMAC scheme with documented assumptions. Replace the header name, signing method and payload fields with the values in your TXTPro integration documentation.
Can I use this receiver with Express 4?
The code is written and tested for Express 5. The same pattern works in Express 4, but check middleware and error-handling differences when you adapt it.
Sources and further reading
Editorial note: This article is written by the TXTPro editorial team (KSVL Solutions) for general information. Regulations and platform policies change; check the linked official sources and seek professional advice for your situation. See our editorial standards.
