Build your first webhook endpoint
A webhook endpoint is a POST route that reads the raw request body, verifies the sender’s signature, ignores event IDs it has already seen, and returns a 2xx within a few seconds. This tutorial builds one in Node.js, gives the same receiver in Python and Go, and then sends it signed test requests so you can watch it accept a real delivery and reject forged, tampered, and stale ones.
The examples verify the Standard Webhooks scheme, which Svix and other providers sign with. For what an endpoint is and how it differs from an API route, see what is a webhook endpoint. For running one in production, see best practices for receiving webhooks.
What the endpoint checks, in order
Every delivery arrives as a POST with three headers: webhook-id, a unique message ID; webhook-timestamp, the send time in Unix seconds; and webhook-signature, one or more space-separated v1,<base64> values. The handler runs five checks before it trusts the body:
- Read the body as raw bytes, before any JSON middleware touches it.
- Reject the request if
webhook-timestampis more than 300 seconds from your clock. - Base64-decode the part of your secret after
whsec_, and use those bytes as the HMAC-SHA256 key over{webhook-id}.{webhook-timestamp}.{raw body}. - Compare the base64 result against each
v1,value in constant time. More than one value appears while the sender is rotating secrets. - Skip the event if its
webhook-idhas been processed before, then respond 2xx and do slow work afterwards.
Steps 1 and 3 are where first endpoints usually break. A JSON parser that re-serializes the body changes its bytes, and using the literal whsec_... string as the key produces signatures that never match. Both show up as a 401 on every request, which makes it tempting to switch verification off. The webhook signature page explains why the check has to stay.
Step 1: Create the project
mkdir webhook-receiver && cd webhook-receiver
npm init -y
npm install express
export WEBHOOK_SECRET=whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw
That secret is a published example value. In a real integration the sender shows you the secret when you register the endpoint, and it belongs in a secrets manager rather than your shell history.
Step 2: Write the receiver
Save this as server.js:
const express = require('express');
const crypto = require('crypto');
const app = express();
const secret = Buffer.from(process.env.WEBHOOK_SECRET.replace(/^whsec_/, ''), 'base64');
const TOLERANCE_SECONDS = 300;
const seen = new Set();
function verify(headers, rawBody) {
const id = headers['webhook-id'];
const timestamp = headers['webhook-timestamp'];
const signatures = headers['webhook-signature'];
if (!id || !timestamp || !signatures) return false;
const age = Math.abs(Date.now() / 1000 - Number(timestamp));
if (!Number.isFinite(age) || age > TOLERANCE_SECONDS) return false;
const expected = crypto
.createHmac('sha256', secret)
.update(`${id}.${timestamp}.`)
.update(rawBody)
.digest();
return signatures.split(' ').some((entry) => {
const [version, value] = entry.split(',');
if (version !== 'v1' || !value) return false;
const candidate = Buffer.from(value, 'base64');
return candidate.length === expected.length && crypto.timingSafeEqual(candidate, expected);
});
}
app.post('/webhooks', express.raw({ type: 'application/json', limit: '1mb' }), (req, res) => {
if (!verify(req.headers, req.body)) {
return res.status(401).send('invalid signature');
}
const id = req.headers['webhook-id'];
if (seen.has(id)) return res.status(200).send('duplicate');
seen.add(id);
const event = JSON.parse(req.body.toString('utf8'));
console.log(`received ${event.type} (${id})`);
res.status(200).send('ok');
});
app.listen(3000, () => console.log('listening on http://localhost:3000/webhooks'));
express.raw hands the route a Buffer of the exact bytes received, capped at 1 MB so an oversized body is refused with a 413 before any work happens. crypto.timingSafeEqual throws when the two buffers differ in length, which is why the length check runs first. The seen set stands in for a database table with a unique constraint on the ID. An in-memory set forgets everything on restart, so a sender retrying after your deploy would get the event processed twice. In production, insert the ID in the same transaction that records the event, so a crash between the two cannot drop it.
Start the server with node server.js.
Step 3: Send it signed test requests
You do not need a provider to test the endpoint. Save this as send-test.js. It signs a sample invoice.paid event the same way a Standard Webhooks sender does:
const crypto = require('crypto');
const secret = Buffer.from(process.env.WEBHOOK_SECRET.replace(/^whsec_/, ''), 'base64');
const id = process.env.ID || `msg_${crypto.randomUUID()}`;
const timestamp = Math.floor(Date.now() / 1000) - Number(process.env.AGE || 0);
const body = JSON.stringify({ type: 'invoice.paid', data: { id: 'in_1042', amount: 4900 } });
const signature = crypto
.createHmac('sha256', secret)
.update(`${id}.${timestamp}.${body}`)
.digest('base64');
fetch('http://localhost:3000/webhooks', {
method: 'POST',
headers: {
'content-type': 'application/json',
'webhook-id': id,
'webhook-timestamp': String(timestamp),
'webhook-signature': `v1,${signature}`,
},
body: process.env.TAMPER ? body.replace('4900', '1') : body,
}).then(async (res) => console.log(res.status, await res.text()));
Run it four ways, on Node 18 or later for the built-in fetch:
node send-test.js # 200 ok
TAMPER=1 node send-test.js # 401 invalid signature
AGE=600 node send-test.js # 401 invalid signature
ID=msg_1 node send-test.js && ID=msg_1 node send-test.js # 200 ok, then 200 duplicate
The second run changes the amount after signing, which is what an attacker editing a captured request looks like. The third backdates the timestamp by ten minutes, a replay attack arriving after the tolerance window closed. The last pair is a retry: the second copy gets a 2xx so the sender stops retrying, but the handler does nothing with it. If the first run returns 401, check the key decoding before anything else.
To test your HMAC code against a known answer, the secret above with ID msg_p5jXN8AQM9LWM0D4loKWxJek, timestamp 1614265330, and body {"test": 2432232314} must produce v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=. That timestamp is years old, so call the signing step directly rather than going through the route, which would reject it as stale.
The same receiver in Python
Flask exposes the raw bytes through request.get_data(), and setting MAX_CONTENT_LENGTH makes it answer 413 for anything over 1 MB.
import base64, hashlib, hmac, json, os, time
from flask import Flask, request
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 1024 * 1024
SECRET = base64.b64decode(os.environ["WEBHOOK_SECRET"].removeprefix("whsec_"))
seen = set()
def verify(headers, raw_body):
msg_id = headers.get("webhook-id")
timestamp = headers.get("webhook-timestamp")
signatures = headers.get("webhook-signature")
if not (msg_id and timestamp and signatures):
return False
try:
if abs(time.time() - int(timestamp)) > 300:
return False
except ValueError:
return False
signed = f"{msg_id}.{timestamp}.".encode() + raw_body
expected = base64.b64encode(hmac.new(SECRET, signed, hashlib.sha256).digest())
return any(
version == "v1" and hmac.compare_digest(value.encode(), expected)
for version, _, value in (s.partition(",") for s in signatures.split(" "))
)
@app.post("/webhooks")
def webhooks():
raw_body = request.get_data()
if not verify(request.headers, raw_body):
return "invalid signature", 401
msg_id = request.headers["webhook-id"]
if msg_id in seen:
return "duplicate", 200
seen.add(msg_id)
event = json.loads(raw_body)
print(f"received {event['type']} ({msg_id})")
return "ok", 200
if __name__ == "__main__":
app.run(port=3000)
The same receiver in Go
The standard library covers all of it: http.MaxBytesReader caps the body, and hmac.Equal is the constant-time comparison.
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"io"
"log"
"math"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
)
var (
secret []byte
seen sync.Map
)
func verify(h http.Header, body []byte) bool {
id, ts, sigs := h.Get("webhook-id"), h.Get("webhook-timestamp"), h.Get("webhook-signature")
if id == "" || ts == "" || sigs == "" {
return false
}
sent, err := strconv.ParseInt(ts, 10, 64)
if err != nil || math.Abs(float64(time.Now().Unix()-sent)) > 300 {
return false
}
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(id + "." + ts + "."))
mac.Write(body)
expected := mac.Sum(nil)
for _, entry := range strings.Split(sigs, " ") {
version, value, ok := strings.Cut(entry, ",")
if !ok || version != "v1" {
continue
}
candidate, err := base64.StdEncoding.DecodeString(value)
if err == nil && hmac.Equal(candidate, expected) {
return true
}
}
return false
}
func webhookHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
if err != nil {
http.Error(w, "body too large", http.StatusRequestEntityTooLarge)
return
}
if !verify(r.Header, body) {
http.Error(w, "invalid signature", http.StatusUnauthorized)
return
}
id := r.Header.Get("webhook-id")
if _, duplicate := seen.LoadOrStore(id, true); duplicate {
w.Write([]byte("duplicate"))
return
}
var event struct {
Type string `json:"type"`
}
if err := json.Unmarshal(body, &event); err != nil {
http.Error(w, "invalid JSON", http.StatusBadRequest)
return
}
log.Printf("received %s (%s)", event.Type, id)
w.Write([]byte("ok"))
}
func main() {
var err error
secret, err = base64.StdEncoding.DecodeString(strings.TrimPrefix(os.Getenv("WEBHOOK_SECRET"), "whsec_"))
if err != nil {
log.Fatal("WEBHOOK_SECRET must be whsec_ followed by base64")
}
http.HandleFunc("/webhooks", webhookHandler)
log.Println("listening on http://localhost:3000/webhooks")
log.Fatal(http.ListenAndServe(":3000", nil))
}
All three listen on port 3000, so send-test.js exercises the Python and Go versions unchanged.
Step 4: Receive a real delivery
Senders need a public HTTPS webhook URL, and localhost is not one. Run ngrok http 3000 or svix listen http://localhost:3000/webhooks, register the printed URL with the sender, and trigger a test event from its dashboard. The request should log a received line just as the test script did. The webhook testing guide covers tunnels, capture tools, and failure testing in more depth.
Before you ship it
Three changes turn this tutorial into a production endpoint. Replace the in-memory set with a database table. Push the event onto a queue and respond before processing it, so slow work never pushes you past the sender’s timeout. And log each delivery’s ID and verification result, so a missing event can be traced. Webhook security 101 walks through the attacks each check above defends against.
If you would rather not maintain verification code at all, the Svix libraries run the same checks in one call, new Webhook(secret).verify(body, headers) in Node.js, with equivalents for Python, Go, and other languages.