A webhook endpoint is a public door to your server. If you don't lock it, anyone can send a fake request saying payment_success: true, and your app might unlock premium features for free.
1. Verify the Signature (HMAC)
This is the gold standard. Providers like Stripe and GitHub sign every request using a secret key only you know.
const stripe = require('stripe');
const endpointSecret = "whsec_...";
app.post('/webhook', express.raw({type: 'application/json'}), (request, response) => {
const sig = request.headers['stripe-signature'];
try {
// If this passes, the request is definitely from Stripe
const event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
} catch (err) {
response.status(400).send(`Webhook Error: ${err.message}`);
return;
}
});
2. Check Timestamps (Replay Attacks)
A hacker might intercept a valid request and "replay" it 10 minutes later to trigger a duplicate action. Always check the timestamp header. If the request is older than 5 minutes, reject it.
3. Use a Middleware Shield
Writing signature verification code for every provider (Stripe, Twilio, SendGrid) is tedious and error-prone.
WebHookGuard handles this security layer for you. We verify the signatures at our edge. We only forward requests to your server if they are authentic.