Function Signature
Description
Creates a middleware function for use in Express-compatible web servers for verifying Interaction Webhooks from Discord. This middleware handles signature verification, automatic PING responses, and request body parsing.Parameters
The public key from the Discord developer dashboard. This is used to verify the Ed25519 signature of incoming interaction requests.
Returns
An Express middleware function that validates incoming Discord interaction requests.
Behavior
The middleware performs the following actions:- Signature Validation: Extracts
X-Signature-Ed25519andX-Signature-Timestampheaders and validates the request using theverifyKeyfunction - Invalid Signature Handling: Returns
401 Unauthorizedif the signature is missing or invalid - PING Auto-Response: Automatically responds with
PONGfor Discord’s PING interactions (used for initial endpoint verification) - Body Parsing: Parses the JSON body and attaches it to
req.bodyfor valid interactions - Next Middleware: Calls
next()to pass control to your interaction handler for non-PING interactions
Usage Example
Basic Setup
With Command Handling
Important Notes
If
req.body has been modified by other middleware, the function will attempt to reconstruct the raw buffer, but this is risky and may fail. The middleware will log a warning in this case.Error Handling
The middleware will return a401 Unauthorized response with the message [discord-interactions] Invalid signature in the following cases:
- Missing
X-Signature-Ed25519orX-Signature-Timestampheaders - Invalid signature that fails verification
- Malformed request data
See Also
- verifyKey - Low-level signature verification function
- verifyWebhookEventMiddleware - Middleware for webhook events
- InteractionType - Enum of interaction types
- InteractionResponseType - Enum of response types