Verify Discord webhooks
Discord signs each webhook event with Ed25519, so you can confirm it came from Discord and wasn't changed. Verify X-Signature-Ed25519 with your application's public key, over the X-Signature-Timestamp value followed by the raw body; Discord's discord-interactions package has a helper for this. Incoming webhooks, which you send to a channel, have no signature to verify.
These pages cover the events Discord sends your app. To post messages to a channel, see how to get started with Discord webhooks.
The facts
{timestamp}{raw body} The X-Signature-Timestamp value with the raw body straight after it and no separator.
POST: answer the PING Discord sends a PING with type 0 when you save the URL. Answer 204 with an empty body.
Discord webhook public key
Discord webhook events have no shared secret. You verify them with your application's public key, which isn't your bot token or client secret.
- In the Developer Portal: open your app's General Information page and copy Public Key.
- From the API:
GET /applications/@mereturns the application object, whoseverify_keyis the hex-encoded verification key. - One per application: the webhook docs point to the Interactions docs for validation, so both use the same key.
- Discord's webhook docs describe no test and live split and no way to rotate the key.
Source: Discord docs ↗
Code
// Generated with: discord-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config();
const express = require('express');
const { verifyKey } = require('discord-interactions');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
// Discord webhook endpoint
// IMPORTANT: Use express.raw() — Ed25519 verification needs the exact raw body bytes.
app.post('/webhooks/discord',
express.raw({ type: 'application/json' }),
async (req, res) => {
const publicKey = process.env.DISCORD_PUBLIC_KEY;
if (!publicKey) {
console.error('DISCORD_PUBLIC_KEY is not configured');
return res.status(500).send('Server configuration error');
}
const signature = req.headers['x-signature-ed25519'];
const timestamp = req.headers['x-signature-timestamp'];
if (!signature || !timestamp) {
return res.status(401).send('Missing signature headers');
}
let isValid;
try {
isValid = await verifyKey(req.body, signature, timestamp, publicKey);
} catch {
isValid = false;
}
if (!isValid) {
return res.status(401).send('Invalid request signature');
}
let payload;
try {
payload = JSON.parse(req.body.toString('utf8'));
} catch {
return res.status(400).send('Invalid JSON payload');
}
// type 0 = PING (endpoint validation). Reply 204 with empty body.
if (payload.type === 0) {
console.log('Received Discord PING');
return res.status(204).send();
}
// type 1 = webhook event
if (payload.type === 1 && payload.event) {
const event = payload.event;
console.log(`Received Discord event: ${event.type}`);
switch (event.type) {
case 'APPLICATION_AUTHORIZED':
console.log('App authorized:', {
userId: event.data?.user?.id,
scopes: event.data?.scopes
});
break;
case 'APPLICATION_DEAUTHORIZED':
console.log('App deauthorized:', {
userId: event.data?.user?.id
});
break;
case 'ENTITLEMENT_CREATE':
console.log('Entitlement created:', {
entitlementId: event.data?.id,
userId: event.data?.user_id,
skuId: event.data?.sku_id
});
break;
case 'ENTITLEMENT_UPDATE':
console.log('Entitlement updated:', { entitlementId: event.data?.id });
break;
case 'ENTITLEMENT_DELETE':
console.log('Entitlement deleted:', { entitlementId: event.data?.id });
break;
case 'QUEST_USER_ENROLLMENT':
console.log('Quest enrollment:', {
userId: event.data?.user_id,
questId: event.data?.quest_id
});
break;
case 'LOBBY_MESSAGE_CREATE':
console.log('Lobby message:', {
lobbyId: event.data?.lobby_id,
content: event.data?.content
});
break;
case 'GAME_DIRECT_MESSAGE_CREATE':
console.log('Game DM:', {
channelId: event.data?.channel_id,
content: event.data?.content
});
break;
default:
console.log('Unhandled event type:', event.type);
}
}
// Acknowledge with 204 (no body). Any 2XX within 3s is accepted by Discord.
return res.status(204).send();
}
);
const server = app.listen(PORT, () => {
console.log(`Discord webhook server running on port ${PORT}`);
console.log(`Webhook endpoint: http://localhost:${PORT}/webhooks/discord`);
});
module.exports = { app, server }; // Generated with: discord-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextResponse } from 'next/server';
import { verifyKey } from 'discord-interactions';
export const dynamic = 'force-dynamic';
type DiscordEvent = {
type: string;
timestamp: string;
data?: Record<string, unknown>;
};
type DiscordWebhookPayload = {
version: number;
application_id: string;
type: number; // 0 = PING, 1 = event
event?: DiscordEvent;
};
export async function POST(request: Request) {
const publicKey = process.env.DISCORD_PUBLIC_KEY;
if (!publicKey) {
console.error('DISCORD_PUBLIC_KEY is not configured');
return new NextResponse('Server configuration error', { status: 500 });
}
const signature = request.headers.get('x-signature-ed25519');
const timestamp = request.headers.get('x-signature-timestamp');
if (!signature || !timestamp) {
return new NextResponse('Missing signature headers', { status: 401 });
}
// Read raw body BEFORE parsing — Ed25519 verification operates on raw bytes.
const rawBody = await request.text();
let isValid: boolean;
try {
isValid = await verifyKey(rawBody, signature, timestamp, publicKey);
} catch {
isValid = false;
}
if (!isValid) {
return new NextResponse('Invalid request signature', { status: 401 });
}
let payload: DiscordWebhookPayload;
try {
payload = JSON.parse(rawBody);
} catch {
return new NextResponse('Invalid JSON payload', { status: 400 });
}
// type 0 = PING (endpoint validation). Reply 204 with empty body.
if (payload.type === 0) {
console.log('Received Discord PING');
return new NextResponse(null, { status: 204 });
}
// type 1 = webhook event
if (payload.type === 1 && payload.event) {
const event = payload.event;
const data = (event.data ?? {}) as Record<string, unknown>;
console.log(`Received Discord event: ${event.type}`);
switch (event.type) {
case 'APPLICATION_AUTHORIZED':
console.log('App authorized:', {
userId: (data.user as { id?: string } | undefined)?.id,
scopes: data.scopes
});
break;
case 'APPLICATION_DEAUTHORIZED':
console.log('App deauthorized:', {
userId: (data.user as { id?: string } | undefined)?.id
});
break;
case 'ENTITLEMENT_CREATE':
console.log('Entitlement created:', {
entitlementId: data.id,
userId: data.user_id,
skuId: data.sku_id
});
break;
case 'ENTITLEMENT_UPDATE':
console.log('Entitlement updated:', { entitlementId: data.id });
break;
case 'ENTITLEMENT_DELETE':
console.log('Entitlement deleted:', { entitlementId: data.id });
break;
case 'QUEST_USER_ENROLLMENT':
console.log('Quest enrollment:', {
userId: data.user_id,
questId: data.quest_id
});
break;
case 'LOBBY_MESSAGE_CREATE':
console.log('Lobby message:', {
lobbyId: data.lobby_id,
content: data.content
});
break;
case 'GAME_DIRECT_MESSAGE_CREATE':
console.log('Game DM:', {
channelId: data.channel_id,
content: data.content
});
break;
default:
console.log('Unhandled event type:', event.type);
}
}
return new NextResponse(null, { status: 204 });
} # Generated with: discord-webhooks skill
# https://github.com/hookdeck/webhook-skills
import json
import os
from typing import Optional
from dotenv import load_dotenv
from fastapi import FastAPI, Header, Request, Response
from nacl.exceptions import BadSignatureError
from nacl.signing import VerifyKey
load_dotenv()
app = FastAPI(title="Discord Webhook Handler")
def verify_discord_signature(
body: bytes,
signature: str,
timestamp: str,
public_key: str,
) -> bool:
"""Verify a Discord webhook request using Ed25519.
Signed content: ``timestamp + raw_body`` (byte concatenation).
"""
try:
verify_key = VerifyKey(bytes.fromhex(public_key))
verify_key.verify(timestamp.encode() + body, bytes.fromhex(signature))
return True
except (BadSignatureError, ValueError):
return False
@app.get("/health")
async def health_check():
return {"status": "ok"}
@app.post("/webhooks/discord")
async def discord_webhook(
request: Request,
x_signature_ed25519: Optional[str] = Header(None),
x_signature_timestamp: Optional[str] = Header(None),
):
public_key = os.environ.get("DISCORD_PUBLIC_KEY")
if not public_key:
print("DISCORD_PUBLIC_KEY is not configured")
return Response(content="Server configuration error", status_code=500)
if not x_signature_ed25519 or not x_signature_timestamp:
return Response(content="Missing signature headers", status_code=401)
body = await request.body()
if not verify_discord_signature(body, x_signature_ed25519, x_signature_timestamp, public_key):
return Response(content="Invalid request signature", status_code=401)
try:
payload = json.loads(body)
except json.JSONDecodeError:
return Response(content="Invalid JSON payload", status_code=400)
payload_type = payload.get("type")
# type 0 = PING (endpoint validation). Reply 204 with empty body.
if payload_type == 0:
print("Received Discord PING")
return Response(status_code=204)
# type 1 = webhook event
if payload_type == 1:
event = payload.get("event") or {}
event_type = event.get("type")
data = event.get("data") or {}
print(f"Received Discord event: {event_type}")
if event_type == "APPLICATION_AUTHORIZED":
user = data.get("user") or {}
print(f"App authorized for user: {user.get('id')}, scopes: {data.get('scopes')}")
elif event_type == "APPLICATION_DEAUTHORIZED":
user = data.get("user") or {}
print(f"App deauthorized for user: {user.get('id')}")
elif event_type == "ENTITLEMENT_CREATE":
print(
"Entitlement created: "
f"id={data.get('id')} user_id={data.get('user_id')} sku_id={data.get('sku_id')}"
)
elif event_type == "ENTITLEMENT_UPDATE":
print(f"Entitlement updated: id={data.get('id')}")
elif event_type == "ENTITLEMENT_DELETE":
print(f"Entitlement deleted: id={data.get('id')}")
elif event_type == "QUEST_USER_ENROLLMENT":
print(
"Quest enrollment: "
f"user_id={data.get('user_id')} quest_id={data.get('quest_id')}"
)
elif event_type == "LOBBY_MESSAGE_CREATE":
print(
"Lobby message: "
f"lobby_id={data.get('lobby_id')} content={data.get('content')!r}"
)
elif event_type == "GAME_DIRECT_MESSAGE_CREATE":
print(
"Game DM: "
f"channel_id={data.get('channel_id')} content={data.get('content')!r}"
)
else:
print(f"Unhandled event type: {event_type}")
# Acknowledge with 204 (no body). Any 2XX within 3s is accepted by Discord.
return Response(status_code=204)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=3000) Or install the Discord webhooks skill:
npx skills add hookdeck/webhook-skills --skill discord-webhooks
Common failures
Body changed before verification
The signature covers the body exactly as Discord sent it. Verify the raw body before any JSON parser touches it.
A separator in the signed message
Discord signs the timestamp and body joined directly. A template with a dot between them, as other vendors use, never matches.
Wrong key
Use the Public Key of the app the URL is registered to, decoded from hex. A bot token, a client secret or another app's key won't verify.
Answering PING before verifying
Check the signature first on every request. A handler that returns early for PING answers a forged request with a 204, and Discord's checks send invalid signatures.
Queue Discord deliveries before they reach your handler.
Event Gateway accepts each Discord delivery, queues it and retries failures on your schedule, with a log of every attempt.