Menu

Discord Notification Integration

This guide will walk you through configuring a Discord webhook and using the utility method sendDiscordNotification, enabling you to receive timely notifications through Discord.

Create Discord Webhook

  1. Open your Discord server and create a dedicated channel for notifications.

If it's for internal notifications, enable Privacy Channel. If it's for public notifications visible to all members, disable it.

create channel
  1. Open channel settings
channel settings
  1. Create a new Webhook and copy the Webhook URL
create webhook
create webhook

Paste the Webhook URL into the environment variable DISCORD_WEBHOOK_URL. If you create multiple Webhook URLs, you can add additional environment variables or hardcode them directly into your code.

sendDiscordNotification Overview and Usage

sendDiscordNotification is located in lib/discord/notifications.ts and requires two parameters:

  • webhookUrl: The Webhook URL copied in the previous step. When you don't provide an explicit URL, it falls back to process.env.DISCORD_WEBHOOK_URL.
  • payload: This is the notification content, which you need to design based on what you want to display. Examples will be provided in the next step.
lib/discord/notifications.ts
export async function sendDiscordNotification({
  webhookUrl,
  payload,
}: {
  webhookUrl: string;
  payload: DiscordWebhookPayload;
}): Promise<{ success: boolean; error?: string }> {
  webhookUrl = webhookUrl || process.env.DISCORD_WEBHOOK_URL || '';
 
  if (!webhookUrl) {
    const message = "Discord webhook URL not provided";
    console.warn(message);
    return { success: false, error: message };
  }
 
  try {
    const response = await fetch(webhookUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(payload),
    });
 
    if (!response.ok) {
      const errorText = await response.text();
      console.error('Discord webhook failed:', response.status, errorText);
      return {
        success: false,
        error: `Discord webhook failed: ${response.status} ${errorText}`,
      };
    }
 
    console.log('Discord notification sent successfully.');
    return { success: true };
  } catch (error) {
    const errorMessage = getErrorMessage(error);
    console.error('Error sending Discord notification:', errorMessage);
    return { success: false, error: errorMessage };
  }
}

Send Notifications

With the method above, the core work of the sending functionality is designing the notification content.

Discord Payload supports the following elements:

  • content: Plain text (up to 2000 characters).
  • embeds: Array of objects containing title, description, color, fields, footer, thumbnail.
  • fields: Up to 25 per embed; use inline: true for column layout.
  • timestamp: ISO string for embed footer.

Typically, you don't need to write the payload yourself. You just need to tell the AI what information your notification should display and select lib/discord/notifications.ts. The AI will complete this work for you.

Here are simple usage examples:

  • Basic text alert
import { sendDiscordNotification } from '@/lib/discord/notifications';
 
await sendDiscordNotification({
  webhookUrl: '', // Optional; leave empty to use DISCORD_WEBHOOK_URL
  payload: {
    content: `New User: ${user.email}`,
  },
});
  • Rich embed example
await sendDiscordNotification({
  payload: {
    embeds: [
      {
        title: 'New Subscription Upgrade',
        description: `User **${user.name}** has upgraded to **${plan.title}**`,
        color: 0x00ff7f,
        fields: [
          { name: 'Owner', value: user.email, inline: true },
          { name: 'Plan', value: plan.title, inline: true },
        ],
        timestamp: new Date().toISOString(),
        footer: { text: 'Billing Service' },
      },
    ],
  },
});