This guide explains how to implement secure webhook signature verification in Node.js using Express. The verification process ensures that webhook payloads are authentic and haven't been tampered with during transmission.
Overview
When a webhook is sent, the payload is signed with a shared secret using HMAC-SHA256. The signature is included in the request headers. The receiving server must verify this signature before processing the webhook.
Implementation Steps
1. Set Up Environment
First, ensure you have the required dependencies:
npminstallexpressbody-parser
Create an environment variable for your webhook signature key:
WEBHOOK_SIGNATURE_KEY=your_signature_key_here
2. Configure Express Server
You'll need to use the raw body parser to access the original payload for signature verification:
Always use constant-time comparison (crypto.timingSafeEqual)
Verify signatures before processing payloads
Return generic error messages to prevent information leakage
Request Validation
Validate request headers
Implement request timeout
Consider implementing replay protection
Error Handling
Log verification failures
Don't expose internal errors to clients
Implement proper monitoring and alerting
Transport Security
Use HTTPS for all webhook endpoints
Consider implementing rate limiting
Keep dependencies up to date
Testing
To test your webhook endpoint, you can use tools like cURL or Postman. Here's an example cURL command:
# Generate a test signatureSECRET="your_webhook_signature_key_here"PAYLOAD='{"event":"test","data":"example"}'SIGNATURE=$(echo-n"$PAYLOAD"|openssldgst-sha256-hmac"$SECRET"-hex|cut-d' '-f2)# Send test webhookcurl-XPOSThttp://localhost:3000/webhook \-H"Content-Type: application/json" \-H"x-webhook-signature: $SIGNATURE" \-d"$PAYLOAD"
Troubleshooting
Common issues and solutions:
Invalid Signature Errors
Verify the webhook secret matches the one provided in OkDash
Ensure payload hasn't been modified in transit
Check for encoding issues in the payload
Middleware Order
Raw body parser must come before signature verification
JSON parser should not be used before signature verification