当サイトは、一部記事に広告を含みます

Next.js × TypeScriptでSlack通知を実装する方法【Webhook/備忘録】

Webアプリやサーバー処理で、エラーやイベント発生時に Slack に通知を送る方法をまとめました。
ここでは Incoming Webhook を使った通知 の実装手順を紹介します。

1. SlackでWebhook URLを取得

Slack API > Your Apps にアクセス

②「Create New App」 → 「From scratch」を選択

App name と対象 Workspace を入力

④ 左メニューの「Incoming Webhooks」を有効化

⑤「Add New Webhook 」をクリックして通知先のチャンネルを選択

⑥ 表示された Webhook URL をコピー

この URL は外部に漏れないよう注意。

2. 環境変数に追加

Webhook URL はソースコードに直接書かず、環境変数で管理します。

# .env.local
SLACK_WEBHOOK_URL=https://hooks.slack.com/services/YOUR/WEBHOOK/URL

Next.js などで利用する場合は process.env.SLACK_WEBHOOK_URL で参照できます。

3. 通知関数を作成

TypeScript で汎用的に使える関数を作成します。

// lib/slack.ts
export const sendSlackAlert = async (message: string, details?: Record<string, string>) => {
  if (!process.env.SLACK_WEBHOOK_URL) {
    console.warn('Slack webhook URL not configured');
    return;
  }

  try {
    const payload = {
      text: message,
      blocks: details ? [
        {
          type: "section",
          text: { type: "mrkdwn", text: message }
        },
        {
          type: "section",
          fields: Object.entries(details).map(([key, value]) => ({
            type: "mrkdwn",
            text: `*${key}:*\n${value}`
          }))
        }
      ] : undefined
    };

    const response = await fetch(process.env.SLACK_WEBHOOK_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });

    if (!response.ok) {
      console.error('Slack notification failed:', response.statusText);
    }
  } catch (error) {
    console.error('Error sending Slack notification:', error);
  }
};

説明

  • message : Slackに送るメインテキスト
  • details : オブジェクト形式の詳細情報を fields として表示
  • blocks を使うことで、より見やすいメッセージを送信可能
  • 環境変数が設定されていない場合は警告を出して処理を中断
  • fetch で Webhook URL に POST し、失敗した場合はコンソールにエラー出力

4. 利用例

import { sendSlackAlert } from "@/lib/slack";

await sendSlackAlert(alertMessage, {
      type: 'subscription_cancellation_failed',
      uid: uid,
      error: errorMessage,
      timestamp: new Date().toISOString()
});

details を渡すと、Slack のメッセージに key/value 形式で追加情報を整形して表示できます。

---

記事が気に入ったら、ぜひ応援いただけると更新がんばれます☕️

Buy Me A Coffee