A public webhook endpoint accepts a POST from anyone. Without a check, an attacker can send fake data, pretend a payment succeeded and corrupt your database. This tutorial shows how to verify webhook signatures with HMAC in Node.js: an Express server that recomputes the signature from the raw request body with the built-in crypto module and rejects anything that does not match.
Quick answer: Keep the raw request body, compute crypto.createHmac('sha256', secret).update(rawBody).digest('hex'), and compare it to the signature header with crypto.timingSafeEqual() after checking both have the same length. Reject the request with 401 if they differ. Never verify against JSON.stringify(req.body).
- Store the provider’s signing secret in
.env. - Capture the raw body with
express.json({ verify }). - Recompute the HMAC-SHA256 of the raw body in a middleware.
- Compare it in constant time and return 401 on a mismatch.
- Run the test sender: the valid request gets 200, the forged one 401.
In this guide
- Before You Start
- What You Will Build
- Why Unsigned Webhooks Are a Risk
- How Webhook Signatures Work
- Step 1: Set Up the Express Project
- Step 2: Keep the Raw Request Body
- Step 3: Write the HMAC Verification Middleware
- Test It: Send a Valid and a Forged Webhook
- Step 4: Block Replay Attacks with a Timestamp
- If It Still Doesn’t Work
- Frequently Asked Questions
- Next Steps
- Official resources

Before You Start
- Node.js 18 or newer; the test script uses the built-in
fetch. - The signing secret from your provider’s webhook settings. A placeholder works for the local test.
- The provider’s signature format: the header name, the algorithm (usually SHA-256) and whether the signature is hex or Base64. Check their docs.
- Two terminal windows. The tutorial takes about 20 minutes.
What You Will Build
.env– the port and the signing secret.server.js– an Express app with the verification middleware and a protected/webhookroute.test-sender.js– a script that plays the provider: it signs a payload and sends one valid and one forged request.
Why Unsigned Webhooks Are a Risk
A webhook receiver is a public entry point into your backend. When Stripe or Shopify sends a POST, your app processes it. If an attacker finds the URL, they can send a crafted JSON payload that claims a $1,000 payment.
Allowing only the provider’s IP addresses sounds like an easy fix, but it is hard to maintain. Providers change their IP ranges, and you would manage firewall rules for every integration.
That is why the major platforms sign their payloads with an HMAC (Hash-based Message Authentication Code). The provider computes the HMAC of the request body with a secret only you and they know. Your server recomputes it; if the two match, the request is genuine.
How Webhook Signatures Work
Verification relies on a shared secret known only to you and the sender:
- The sender builds the payload, usually a JSON string.
- It computes an HMAC of the payload with the shared secret and an algorithm such as SHA-256.
- It puts the result in an HTTP header, such as
x-signatureorstripe-signature. - Your server receives the request, takes the raw body and computes the HMAC with its copy of the secret.
- You compare your result with the header. If they match, you process the request.
Step 1: Set Up the Express Project
You do not need any extra crypto library; Node’s built-in crypto module does everything here. Run this in your terminal:
mkdir webhook-verifier
cd webhook-verifier
npm init -y
npm install express dotenvNext, create a .env file in the project folder to store the signing secret. Use a placeholder for now and replace it with the provider’s secret later:
PORT=3000
WEBHOOK_SECRET=my_super_secret_signing_keyStep 2: Keep the Raw Request Body
This is the gotcha that trips up most people writing their first webhook receiver. Express apps usually parse JSON with express.json(), which turns the request into a JavaScript object. If you compute the HMAC over JSON.stringify(req.body), verification fails.
The reason is that re-serialising the object does not reproduce the original bytes. Spacing, line breaks, character escaping and number formatting can all differ, and a single changed byte produces a completely different SHA-256 result. You must verify against the exact raw body that came over the wire.
Express’s JSON parser accepts a verify option that gives you the raw body buffer before parsing. This is the pattern; it is already included in server.js in the next step, so you do not need to save it separately:
const express = require('express');
const app = express();
// Capture the raw body buffer for signature verification
app.use(express.json({
verify: (req, res, buf) => {
req.rawBody = buf;
}
}));You keep the parsed req.body for your business logic, and req.rawBody holds the original bytes as a Buffer for the signature check.
Step 3: Write the HMAC Verification Middleware
The middleware reads the signature header, computes its own HMAC with Node’s crypto API and compares the two.
Do not compare them with ===. A normal string comparison stops at the first character that differs, so it takes slightly longer the more characters match. That opens the door to a timing attack, where an attacker guesses the signature one character at a time by measuring response times. crypto.timingSafeEqual() compares buffers in constant time, no matter where a mismatch is.
Create a server.js file with this code:
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');
const app = express();
const PORT = process.env.PORT || 3000;
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET;
if (!WEBHOOK_SECRET) {
console.error('Error: WEBHOOK_SECRET is not defined in environment variables.');
process.exit(1);
}
// Capture raw body buffer
app.use(express.json({
verify: (req, res, buf) => {
req.rawBody = buf;
}
}));
// Middleware to verify HMAC signatures
function verifyWebhookSignature(req, res, next) {
const signatureHeader = req.headers['x-signature'];
if (!signatureHeader) {
return res.status(401).json({ error: 'Missing x-signature header' });
}
if (!req.rawBody) {
return res.status(400).json({ error: 'Missing raw request body' });
}
try {
// Create HMAC using SHA-256 and our shared secret
const hmac = crypto.createHmac('sha256', WEBHOOK_SECRET);
hmac.update(req.rawBody);
const calculatedSignature = hmac.digest('hex');
// Convert both signatures to buffers for timingSafeEqual
const trustedBuffer = Buffer.from(calculatedSignature, 'hex');
const receivedBuffer = Buffer.from(signatureHeader, 'hex');
// Check length first: timingSafeEqual throws if the buffers differ in length
if (trustedBuffer.length !== receivedBuffer.length) {
return res.status(401).json({ error: 'Invalid signature' });
}
// Use timing-safe comparison to prevent timing attacks
const isValid = crypto.timingSafeEqual(trustedBuffer, receivedBuffer);
if (!isValid) {
return res.status(401).json({ error: 'Invalid signature' });
}
next();
} catch (err) {
console.error('Signature verification failed:', err.message);
return res.status(500).json({ error: 'Internal verification error' });
}
}
// Protected webhook route
app.post('/webhook', verifyWebhookSignature, (req, res) => {
console.log('Verified Webhook Received:', req.body);
res.status(200).json({ received: true });
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});timingSafeEqual throws if the buffers have different lengths, which is why the code checks the length first and returns 401.
Test It: Send a Valid and a Forged Webhook
To test, you need a script that acts as the webhook provider: it signs a payload with the same secret and POSTs it to your server. Create a file named test-sender.js:
require('dotenv').config();
const crypto = require('crypto');
// Read the secret from .env instead of hard-coding it in the script
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET;
const url = 'http://localhost:3000/webhook';
const payload = JSON.stringify({
event: 'order.completed',
data: {
orderId: 'order_987654321',
amount: 99.99,
currency: 'USD'
}
});
// Generate signature using the same secret and algorithm
const hmac = crypto.createHmac('sha256', WEBHOOK_SECRET);
hmac.update(payload);
const signature = hmac.digest('hex');
async function sendWebhook(sendValidSignature = true) {
const headers = {
'Content-Type': 'application/json',
'x-signature': sendValidSignature ? signature : 'fake_signature_to_test_security'
};
try {
const response = await fetch(url, { method: 'POST', headers: headers, body: payload });
const data = await response.json();
console.log(`Status: ${response.status}`, data);
} catch (error) {
console.error('Error sending webhook:', error.message);
}
}
(async () => {
console.log('Testing with valid signature...');
await sendWebhook(true);
console.log('\nTesting with invalid signature...');
await sendWebhook(false);
})();Start the server in your first terminal:
node server.jsYou should see Server running on port 3000. Then run the test script in the second terminal:
node test-sender.jsThe script prints Status: 200 with { received: true } for the valid signature, then Status: 401 with { error: 'Invalid signature' } for the forged one. The server terminal logs Verified Webhook Received: with the order payload only once, for the first request.
To test with a real provider, test webhooks locally using Cloudflare Tunnels to give your local server a public URL.
Step 4: Block Replay Attacks with a Timestamp
An HMAC proves the payload was not changed, but it does not stop replay attacks. If an attacker captures a valid signed request, they can send the same payload and signature again, and your server will accept it.
To prevent this, providers such as Stripe include a timestamp in the signature header, in a format like t=1672531199,v1=6a8b9c.... You then:
- Read the timestamp (
t) and the signature (v1) from the header. - Reject the request if the timestamp is more than about 5 minutes away from your server’s clock.
- Compute the HMAC over the timestamp, a dot and the raw body, and compare it in constant time.
Add this function to server.js and use it on the route in place of verifyWebhookSignature:
function verifyWebhookWithTimestamp(req, res, next) {
// Format: t=1672531199,v1=hash
const header = req.headers['x-signature'];
if (!header) return res.status(401).json({ error: 'Missing signature' });
if (!req.rawBody) return res.status(400).json({ error: 'Missing raw request body' });
const parts = header.split(',');
const timestampPart = parts.find(p => p.startsWith('t='));
const signaturePart = parts.find(p => p.startsWith('v1='));
if (!timestampPart || !signaturePart) {
return res.status(401).json({ error: 'Invalid header format' });
}
const timestampString = timestampPart.split('=')[1];
const timestamp = parseInt(timestampString, 10);
const signature = signaturePart.split('=')[1];
// Check if request is older than 5 minutes (300 seconds)
const now = Math.floor(Date.now() / 1000);
if (Number.isNaN(timestamp) || Math.abs(now - timestamp) > 300) {
return res.status(401).json({ error: 'Request expired' });
}
// Recreate the signature over "timestamp.rawBody", hashing the body bytes exactly as received
const hmac = crypto.createHmac('sha256', WEBHOOK_SECRET);
hmac.update(`${timestampString}.`);
hmac.update(req.rawBody);
const calculatedSignature = hmac.digest('hex');
const trustedBuffer = Buffer.from(calculatedSignature, 'hex');
const receivedBuffer = Buffer.from(signature, 'hex');
if (trustedBuffer.length !== receivedBuffer.length) {
return res.status(401).json({ error: 'Invalid signature' });
}
if (!crypto.timingSafeEqual(trustedBuffer, receivedBuffer)) {
return res.status(401).json({ error: 'Invalid signature' });
}
next();
}To test it, change test-sender.js to sign the string `${t}.${payload}`, where t is Math.floor(Date.now() / 1000), and send the header as t=…,v1=…. The pattern follows Stripe’s webhook signature docs, a good reference for secure webhook design.
If It Still Doesn’t Work
- Genuine provider requests get 401
Invalid signature: check that you use the right secret (test and live secrets often differ) and that.envhas no extra spaces or quotes around it. - Still 401 with the right secret: the provider may send the signature in Base64 rather than hex. Use
digest('base64')andBuffer.from(signatureHeader, 'base64'), and check the exact header name in their docs. - 400
Missing raw request body: the request did not have a JSON content type, so the parser and itsverifyfunction never ran. Check the provider sendsContent-Type: application/json. - The server exits with
WEBHOOK_SECRET is not defined: the.envfile is missing or not in the folder you start the server from. fetch is not definedin the test script: your Node.js version is older than 18. Upgrade Node.js.
Frequently Asked Questions
Should I use the provider’s SDK to verify signatures?
Yes, if the provider offers one. Stripe, Shopify and Clerk ship official helpers that do the parsing and timing-safe comparison for you. Stripe’s SDK, for example, has stripe.webhooks.constructEvent(), which takes the raw body you pass in and handles timestamp extraction and the comparison. Write your own check only when no SDK exists.
What should I do if signature verification fails?
Return 401 Unauthorized or 403 Forbidden immediately and stop. Do not run database queries or start background jobs. Log the failure on your side so you can debug it, but do not return detailed error messages to the client, because they help an attacker adjust their forgery.
Why does verification pass locally but fail in production?
Usually something in front of your app changes the body before Express sees it. Reverse proxies, API gateways and serverless platforms such as AWS Lambda or Vercel may parse or re-encode the request. If anything strips headers, changes line endings or parses the JSON first, the raw bytes no longer match and verification fails.
Next Steps
Your webhook endpoint now rejects requests that were not signed with your secret. Swap in your provider’s secret, header name and encoding, and add the timestamp check if the provider sends one. After the signature passes, check the payload’s shape before touching the database; see how to validate webhook payloads with Zod. If you also send webhooks of your own, the guide to building a webhook retry system covers delivery failures.

