Integrating Discord Notifications in Express.js for Error Handling

Learn how to set up Discord notifications in your Express.js server to notify you whenever an error occurs, using Discord webhooks.


In this guide, we’ll walk through the steps to integrate Discord notifications into your Express.js server. This will allow you to receive real-time alerts in a Discord channel whenever an error occurs in your application.

Setup Process

1. Create a Discord Server

If you don't have a Discord server already, follow these steps:

2. Create a Webhook

3. Set Up the Express.js Application

Install the necessary packages in your Express app:

npm install express axios

Now, in your Express.js application, implement error handling and webhook integration as shown below.

4. Add Error Handling and Discord Notification Code

const express = require('express');
const axios = require('axios');
const app = express();
 
// Your Discord Webhook URL
const DISCORD_WEBHOOK_URL = 'your-discord-webhook-url';
 
// Middleware to catch errors and send notifications
app.use((err, req, res, next) => {
  // Log the error
  console.error(err.status, err.message, err.type, err.controller);
 
  // Send a message to Discord
  axios.post(DISCORD_WEBHOOK_URL, {
    content: `<@USER_ID>, an error occurred:\n\n` +
             `\`\`\`diff\n- Status: ${err.status}\n\`\`\`\n` +
             `**Message:** ${err.message}\n` +
             `**Type:** ${err.type || 'N/A'}\n` +
             `**Controller:** ${err.controller || 'N/A'}`
  })
  .then(() => {
    console.log('Notification sent to Discord');
  })
  .catch(error => {
    console.error('Error sending notification to Discord:', error);
  });
 
  res.status(500).send('Something went wrong!');
});
 
// Your other routes...
 
app.listen(3000, () => {
  console.log('Server running on port 3000');
});

5. Mention a User in Discord Notifications

To mention a specific user in Discord, you need their User ID. Enable Developer Mode in Discord to copy the user’s ID:

Once you have the user’s ID, include it in the webhook message like this:

content: `<@1234567890>, an error occurred:\n\n`

Replace 1234567890 with the actual User ID.

Conclusion

By following these steps, you have successfully integrated Discord notifications into your Express.js application for error handling. Happy coding!