Skip to content

Slack Notifications with Forest Notifications App

This document explains how to set up and use the Forest Notifications App to send notifications to Slack channels using Slack's Incoming Webhooks feature. The implementation leverages the Forest Notifications App created by Lucas to unify and simplify Slack notifications across various workflows. This document is intended for developers who need to integrate new notifications or extend existing ones.


Overview Diagram

Below is an overview of how Slack notifications are structured and integrated with the Forest Notifications App.

diagram

  • Your App: This is where you define the logic to send notifications, such as specific events like form submissions or updates.
  • Forest Notifications App: A centralized Slack app where webhooks are managed. This allows for flexibility in routing messages to different channels.
  • Slack API: The final endpoint where formatted messages appear in the specified Slack channel.

Your application sends structured payloads to the Forest Notifications App, which then forwards the data to the specified Slack webhook using the Slack API.

Note

Slack's "Incoming Webhooks" are actually simple HTTP endpoints that accept POST requests to send messages to Slack channels. While they're called webhooks, they function more like a push API endpoint than traditional webhooks that send data to your application.


Components of the Implementation

Here’s a breakdown of each component involved in the Slack notification system:

1. Forest Notifications App

The Forest Notifications App acts as a central hub for managing Slack Incoming Webhooks. Key functionalities include:

  • Incoming Webhook Configuration: Each Slack channel can have its own Incoming Webhook URL, configured in the Forest Notifications App.
  • Message Formatting: Centralized logic for consistent formatting of Slack messages.
  • Extensibility: Easily add new webhooks or channels as requirements grow.

Steps to Create and Manage Webhooks in the Forest Notifications App

  1. Go to the Forest Notifications App.
  2. Generate a webhook URL for each channel you want to send notifications to.
  3. Save the webhook URLs securely (e.g., in Doppler).

2. Nuxt 3 Application (Frontend)

Note

For this example we will use Nuxt 3 for our application, but it can be any framework/programming language.

The Nuxt 3 application triggers notifications by sending structured payloads to the /api/notifications/slack endpoint.

Key Code Snippets

In any application component, you can call the /api/notifications/slack endpoint as follows:

const sendNotification = async (payload) => {
  try {
    await $fetch('/api/notifications/slack', {
      method: 'POST',
      body: payload,
    });
    console.log('Notification sent successfully');
  } catch (error) {
    console.error('Error sending notification:', error);
  }
};

sendNotification({
  message: 'Hello World!'
});

The endpoint is implemented as follows:

import { readBody, createError } from 'h3';

export default defineEventHandler(async (event) => {
  const webhookUrl = process.env.SLACK_WEBHOOK_URL;
  if (!webhookUrl) {
    throw createError({
      statusCode: 500,
      statusMessage: 'Slack webhook URL not configured',
    });
  }

  const body = await readBody(event);
  const { message } = body;

  if (!message) {
    throw createError({
      statusCode: 400,
      statusMessage: 'Missing required parameter: message',
    });
  }

  const payload = { text: message };

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

    if (!response.ok) {
      throw new Error(`Failed to send Slack message: ${response.statusText}`);
    }

    return { success: true };
  } catch (error) {
    throw createError({
      statusCode: 500,
      statusMessage: `Error sending Slack notification: ${error.message}`,
    });
  }
});

3. Slack API

Slack’s API handles the delivery of messages to the specified channel. Each webhook URL is associated with a specific channel.

Example Payload Sent to Slack

Below is an example payload sent to the Slack API:

curl -X POST -H 'Content-type: application/json' \
--data '{"text":"Hello, World!"}' \
https://hooks.slack.com/services/XXXXXXXXXXX/YYYYYYYYYYYY/ABCdEFgHiJkLmNoPqRsTuv

Customization for Future Implementations

The current implementation supports:

  • Adding New Channels: Add new webhooks to the Forest Notifications App.
  • Custom Message Formats: Update the message formatting logic in the payload.
  • Support for Multiple Workflows: Extend the logic to handle different types of notifications.

For example, if you need to notify a different channel or send a message in response to a new type of event, you can:

  1. Add a new webhook URL in the Forest Notifications App.
  2. Update the endpoint handler to include the new event type.
  3. Test the workflow by triggering the new event from your application.

Customizing Slack Alerts

The Slack API provides robust options for creating rich, interactive messages using Block Kit Builder.

Interactive Message Components

  • Blocks: Building blocks for your messages (sections, dividers, buttons)
  • Interactive Elements: Buttons, dropdowns, date pickers
  • Rich Text: Formatting options, emojis, and mentions
  • Attachments: Media and formatted content

Tip

Use the Block Kit Builder to design and preview your messages in real-time before implementing them.

const richMessage = {
  blocks: [
    {
      type: "section",
      text: {
        type: "mrkdwn",
        text: "*New Alert*\nImportant notification from the system"
      }
    },
    {
      type: "actions",
      elements: [
        {
          type: "button",
          text: {
            type: "plain_text",
            text: "View Details"
          },
          url: "https://example.com/details"
        }
      ]
    }
  ]
};

References