Verify RudderStack webhooks
RudderStack doesn't sign webhooks. If you choose Basic Auth on the HTTP Webhook destination, every request carries Authorization: Basic base64(username:password), and comparing those values shows the request came from someone who knows them. It doesn't cover the body and has no timestamp, so use HTTPS. The destination also offers Bearer Token and API Key, which send a static value, and No Auth, the default.
These pages cover the HTTP Webhook destination, which sends RudderStack events to your endpoint. To send webhooks into RudderStack instead, use its Webhook Source. RudderStack's separate Webhook destination has its own settings and isn't covered here.
The facts
RudderStack webhook secret
RudderStack doesn't issue a secret. You choose the credentials and enter them in the destination's connection settings, and it sends them on each request. Keep it in an environment variable, not in source code.
- Set them under Authentication on the destination: Basic Auth takes a Username and Password, Bearer Token a Token, and API Key a Key and Value.
- A new destination defaults to
No Auth, so it sends no credentials until you choose a type. - With Basic Auth the username is 1 to 100 characters and the password at most 100, with no line breaks.
- Credentials belong to one destination. No rotation process is documented, so change them on the destination and your receiver together.
Source: RudderStack docs ↗
Code
// Generated with: rudderstack-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const crypto = require('crypto');
const express = require('express');
const app = express();
/**
* Constant-time string comparison. Hashing both sides first gives equal-length
* buffers, so timingSafeEqual never throws and the secret's length isn't leaked.
*/
function safeEqual(a, b) {
const ha = crypto.createHash('sha256').update(String(a), 'utf8').digest();
const hb = crypto.createHash('sha256').update(String(b), 'utf8').digest();
return crypto.timingSafeEqual(ha, hb);
}
/**
* Parse `Authorization: Basic base64(username:password)`. The scheme is case-insensitive
* and the credentials are split on the FIRST colon, so the password may contain colons.
*/
function parseBasicAuth(header) {
if (!header) return null;
const match = /^basic\s+([A-Za-z0-9+/]+={0,2})\s*$/i.exec(header);
if (!match) return null;
const decoded = Buffer.from(match[1], 'base64').toString('utf8');
const idx = decoded.indexOf(':');
if (idx === -1) return null;
return { username: decoded.slice(0, idx), password: decoded.slice(idx + 1) };
}
/**
* RudderStack does not sign payloads. The HTTP Webhook destination sends the Basic Auth
* credentials you configured. Both values are compared (no short-circuit) before deciding.
*/
function verifyRudderstackRequest(headers, config = process.env) {
const expectedUser = config.RUDDERSTACK_WEBHOOK_USERNAME;
const expectedPass = config.RUDDERSTACK_WEBHOOK_PASSWORD;
if (!expectedUser || !expectedPass) return false; // never accept when unconfigured
const creds = parseBasicAuth(headers['authorization']);
if (!creds) return false;
const userOk = safeEqual(creds.username, expectedUser);
const passOk = safeEqual(creds.password, expectedPass);
return userOk && passOk;
}
function handleEvent(event) {
switch (event.type) {
case 'track':
console.log(`Track: ${event.event} (user ${event.userId || event.anonymousId})`);
// Your code: handle the tracked event (event.event, event.properties)
break;
case 'identify':
console.log(`Identify: user ${event.userId || event.anonymousId}`);
// Your code: sync event.traits to your user store
break;
case 'page':
console.log(`Page: ${event.name || event.properties?.url}`);
// Your code: record the page view
break;
case 'screen':
console.log(`Screen: ${event.name}`);
// Your code: record the screen view
break;
case 'group':
console.log(`Group: ${event.groupId}`);
// Your code: sync event.traits to your account/group store
break;
case 'alias':
console.log(`Alias: ${event.previousId} -> ${event.userId}`);
// Your code: merge the two identities
break;
default:
// Mappings can emit any shape, and warehouse sources send other message types.
console.log(`Unhandled RudderStack payload (type: ${event.type})`);
}
}
const METHODS = ['POST', 'PUT', 'PATCH', 'GET', 'DELETE'];
// The HTTP method is chosen in the destination settings, so accept all of them.
// Read the body raw (any content type) so the request is authenticated before parsing.
app.all('/webhooks/rudderstack', express.raw({ type: '*/*' }), (req, res) => {
if (!METHODS.includes(req.method)) {
res.set('Allow', METHODS.join(', '));
return res.status(405).json({ error: 'Method not allowed' });
}
if (!verifyRudderstackRequest(req.headers)) {
res.set('WWW-Authenticate', 'Basic realm="rudderstack"');
return res.status(401).json({ error: 'Invalid or missing Basic credentials' });
}
const raw = Buffer.isBuffer(req.body) ? req.body.toString('utf8') : '';
let events = [];
// An empty body (e.g. GET) is valid: nothing to process.
if (raw.trim() !== '') {
let payload;
try {
payload = JSON.parse(raw);
} catch {
return res.status(400).json({ error: 'Invalid JSON body' });
}
// Batching sends a JSON array of events.
events = Array.isArray(payload) ? payload : [payload];
if (!events.every((e) => e && typeof e === 'object' && !Array.isArray(e))) {
return res.status(400).json({ error: 'Expected a JSON object or an array of objects' });
}
}
try {
events.forEach(handleEvent);
} catch (err) {
console.error('Error handling RudderStack event:', err);
return res.status(500).json({ error: 'Handler error' });
}
res.status(200).json({ received: true, events: events.length });
});
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
module.exports = app;
module.exports.verifyRudderstackRequest = verifyRudderstackRequest;
module.exports.parseBasicAuth = parseBasicAuth;
if (require.main === module) {
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Webhook endpoint: http://localhost:${PORT}/webhooks/rudderstack`);
});
} // Generated with: rudderstack-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifyRudderstackRequest } from '../../../lib/verify-rudderstack';
type RudderEvent = Record<string, any>;
function handleEvent(event: RudderEvent): void {
switch (event.type) {
case 'track':
console.log(`Track: ${event.event} (user ${event.userId || event.anonymousId})`);
// Your code: handle the tracked event (event.event, event.properties)
break;
case 'identify':
console.log(`Identify: user ${event.userId || event.anonymousId}`);
// Your code: sync event.traits to your user store
break;
case 'page':
console.log(`Page: ${event.name || event.properties?.url}`);
// Your code: record the page view
break;
case 'screen':
console.log(`Screen: ${event.name}`);
// Your code: record the screen view
break;
case 'group':
console.log(`Group: ${event.groupId}`);
// Your code: sync event.traits to your account/group store
break;
case 'alias':
console.log(`Alias: ${event.previousId} -> ${event.userId}`);
// Your code: merge the two identities
break;
default:
// Mappings can emit any shape, and warehouse sources send other message types.
console.log(`Unhandled RudderStack payload (type: ${event.type})`);
}
}
// The HTTP method is chosen in the destination settings, so every method shares one handler.
async function handle(request: NextRequest) {
// Authenticate before reading or parsing the body.
if (!verifyRudderstackRequest(request.headers)) {
return NextResponse.json(
{ error: 'Invalid or missing Basic credentials' },
{ status: 401, headers: { 'WWW-Authenticate': 'Basic realm="rudderstack"' } }
);
}
// Read the raw text so any content type works. An empty body (e.g. GET) is valid.
const raw = await request.text();
let events: unknown[] = [];
if (raw.trim() !== '') {
let payload: unknown;
try {
payload = JSON.parse(raw);
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
// Batching sends a JSON array of events.
events = Array.isArray(payload) ? payload : [payload];
if (!events.every((e) => e && typeof e === 'object' && !Array.isArray(e))) {
return NextResponse.json(
{ error: 'Expected a JSON object or an array of objects' },
{ status: 400 }
);
}
}
try {
(events as RudderEvent[]).forEach(handleEvent);
} catch (err) {
console.error('Error handling RudderStack event:', err);
return NextResponse.json({ error: 'Handler error' }, { status: 500 });
}
return NextResponse.json({ received: true, events: events.length });
}
export const POST = handle;
export const PUT = handle;
export const PATCH = handle;
export const GET = handle;
export const DELETE = handle; # Generated with: rudderstack-webhooks skill
# https://github.com/hookdeck/webhook-skills
import base64
import binascii
import hmac
import json
import os
import re
from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, Request
load_dotenv()
app = FastAPI()
_BASIC_RE = re.compile(r"^basic\s+([A-Za-z0-9+/]+={0,2})\s*$", re.IGNORECASE)
def safe_equal(a: str, b: str) -> bool:
"""Constant-time comparison on bytes (compare_digest raises on non-ASCII str)."""
return hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8"))
def parse_basic_auth(header):
"""Parse `Authorization: Basic base64(username:password)`. The scheme is
case-insensitive and the credentials are split on the FIRST colon, so the
password may contain colons."""
if not header:
return None
match = _BASIC_RE.match(header)
if not match:
return None
try:
decoded = base64.b64decode(match.group(1), validate=True).decode("utf-8")
except (binascii.Error, UnicodeDecodeError):
return None
username, sep, password = decoded.partition(":")
if not sep:
return None
return username, password
def verify_rudderstack_request(headers, config=os.environ) -> bool:
"""RudderStack does not sign payloads. The HTTP Webhook destination sends the
Basic Auth credentials you configured. Both values are compared (no
short-circuit) before deciding."""
expected_user = config.get("RUDDERSTACK_WEBHOOK_USERNAME")
expected_pass = config.get("RUDDERSTACK_WEBHOOK_PASSWORD")
if not expected_user or not expected_pass:
return False # never accept when unconfigured
creds = parse_basic_auth(headers.get("authorization"))
if creds is None:
return False
user_ok = safe_equal(creds[0], expected_user)
pass_ok = safe_equal(creds[1], expected_pass)
return user_ok and pass_ok
async def require_rudderstack_auth(request: Request) -> None:
"""FastAPI dependency: reject the request before the body is parsed."""
if not verify_rudderstack_request(request.headers):
raise HTTPException(
status_code=401,
detail="Invalid or missing Basic credentials",
headers={"WWW-Authenticate": 'Basic realm="rudderstack"'},
)
def handle_event(event: dict) -> None:
kind = event.get("type")
if kind == "track":
print(f"Track: {event.get('event')} (user {event.get('userId') or event.get('anonymousId')})")
# Your code: handle the tracked event (event["event"], event["properties"])
elif kind == "identify":
print(f"Identify: user {event.get('userId') or event.get('anonymousId')}")
# Your code: sync event["traits"] to your user store
elif kind == "page":
print(f"Page: {event.get('name') or (event.get('properties') or {}).get('url')}")
# Your code: record the page view
elif kind == "screen":
print(f"Screen: {event.get('name')}")
# Your code: record the screen view
elif kind == "group":
print(f"Group: {event.get('groupId')}")
# Your code: sync event["traits"] to your account/group store
elif kind == "alias":
print(f"Alias: {event.get('previousId')} -> {event.get('userId')}")
# Your code: merge the two identities
else:
# Mappings can emit any shape, and warehouse sources send other message types.
print(f"Unhandled RudderStack payload (type: {kind})")
# The HTTP method is chosen in the destination settings, so accept all of them.
@app.api_route(
"/webhooks/rudderstack",
methods=["POST", "PUT", "PATCH", "GET", "DELETE"],
dependencies=[Depends(require_rudderstack_auth)],
)
async def rudderstack_webhook(request: Request):
# Read the raw body so any content type works. An empty body (e.g. GET) is valid.
raw_body = await request.body()
events = []
if raw_body.strip():
try:
payload = json.loads(raw_body)
except (json.JSONDecodeError, UnicodeDecodeError):
raise HTTPException(status_code=400, detail="Invalid JSON body")
# Batching sends a JSON array of events.
events = payload if isinstance(payload, list) else [payload]
if not all(isinstance(e, dict) for e in events):
raise HTTPException(
status_code=400, detail="Expected a JSON object or an array of objects"
)
try:
for event in events:
handle_event(event)
except Exception as err: # noqa: BLE001
print(f"Error handling RudderStack event: {err}")
raise HTTPException(status_code=500, detail="Handler error")
return {"received": True, "events": len(events)}
@app.get("/health")
async def health():
return {"status": "ok"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) Or install the RudderStack webhooks skill:
npx skills add hookdeck/webhook-skills --skill rudderstack-webhooks
Common failures
The destination isn't set to Basic Auth
No Auth is the default and sends no Authorization header. Bearer Token and API Key send something else.
Splitting on the wrong colon
RudderStack joins the two values as username:password. Split the decoded value on its first colon, since a password can contain one.
A password changed on one side only
Every request then fails, and RudderStack aborts a 4XX without retrying, so those events don't come back. Change both sides together.
Let Event Gateway check RudderStack credentials.
With Basic Auth on the destination, Event Gateway checks the username and password on each request, and a request that doesn't match never reaches your service. It queues the rest and retries failures on your schedule.