Discord Webhook Events allow your application to receive real-time notifications about activities in Discord servers where your app is installed. Unlike interactions, webhook events are one-way notifications that donβt require an immediate response.
Set your webhook event URL in the Discord Developer Portal under your application settings.
2
Create your webhook endpoint
Use the verifyWebhookEventMiddleware to handle events:
import express from 'express';import { verifyWebhookEventMiddleware, WebhookType } from 'discord-interactions';const app = express();app.post('/events', verifyWebhookEventMiddleware(process.env.CLIENT_PUBLIC_KEY), (req, res) => { console.log('π¨ Event Received!'); console.log(req.body); // Process the event // Note: Response is already sent by middleware (204 No Content) });
3
Handle different event types
Process events based on their type:
app.post('/events', verifyWebhookEventMiddleware(process.env.CLIENT_PUBLIC_KEY), (req, res) => { const event = req.body; switch (event.type) { case WebhookType.PING: // Handled automatically by middleware break; case WebhookType.EVENT: handleEvent(event); break; } });
The verifyWebhookEventMiddleware handles responses automatically:
PING events: Returns 204 No Content
Regular events: Returns 204 No Content and then calls next()
Invalid signatures: Returns 401 Unauthorized
// The middleware handles the response, so you can focus on processingapp.post('/events', verifyWebhookEventMiddleware(process.env.CLIENT_PUBLIC_KEY), (req, res) => { // Response already sent! Just process the event const event = req.body; processEventAsync(event); // Can be async or synchronous });
if (event.data?.event?.type === 'APPLICATION_DEAUTHORIZED') { const { user } = event.data.event; console.log(`App deauthorized by ${user.username}`); // Clean up user data await removeAuthorization(user.id);}
Do not use body-parsing middleware (like body-parser or express.json()) on webhook event routes. The middleware needs access to the raw request body for signature verification.
Webhook events are delivered at-least-once. Design your event handlers to be idempotent to handle potential duplicate deliveries.
Events are processed asynchronously after the 204 response is sent. Make sure your event handlers catch and log errors properly.