What You’ll Learn
- Setting up an Express server for Discord interactions
- Verifying interaction requests with middleware
- Handling slash commands
- Processing Discord webhook events
- Setting up health check endpoints
Prerequisites
Before you begin, make sure you have:
- Node.js installed (v16 or higher)
- A Discord application with a public key
- Your application’s public key stored in environment variables
Complete Example
Key Features
Interaction Endpoint
The/interactions endpoint handles all Discord slash commands and interactions:
- Uses
verifyKeyMiddlewareto automatically verify Discord’s request signature - Responds to application commands with a simple message
- The middleware handles PING interactions automatically
Event Webhook Endpoint
The/events endpoint receives Discord webhook events:
- Uses
verifyWebhookEventMiddlewareto verify event authenticity - Logs all received events for debugging and monitoring
Health Check
A simple health check endpoint for monitoring:Environment Setup
Create a.env file in your project root:
Running the Server
Start your server:http://localhost:8999.
Configure Discord
In your Discord application settings:- Set the Interactions Endpoint URL to:
https://your-domain.com/interactions - (Optional) Set the Webhook URL to:
https://your-domain.com/events
For local development, use a tool like ngrok to expose your local server:
Important Notes
Body Parser Considerations
Body Parser Considerations
If you’re using
body-parser or other middleware that parses request bodies, apply it after your interaction routes. The verifyKeyMiddleware needs access to the raw request body to verify the signature.Recommended approach:Security
Security
The middleware automatically:
- Verifies the
X-Signature-Ed25519header - Validates the
X-Signature-Timestampheader - Rejects invalid requests with a 401 status
CLIENT_PUBLIC_KEY secure and never expose it in client-side code.Next Steps
- Learn about handling modals
- Explore message components
- Deploy to Google Cloud Functions
- Check out the Next.js integration