cloudflare worker to send slack notification in javascript

To send a Slack notification using Cloudflare Workers, you'll need a couple of things:

  1. A Slack webhook URL to send the message to. To get this, follow Slack's instructions for setting up a webhook.

  2. A JavaScript function that sends the message to Slack using the webhook URL. Here's an example function:

async function sendSlackNotification(event) {
  const webhookUrl = '<add your webhook URL here>';  // add your webhook URL here
  const request = new Request(webhookUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    },
    body: JSON.stringify({
      text: 'Hello from Cloudflare Workers!'
    })
  });
  const response = await fetch(request);
  if (response.ok) {
    return new Response('Slack notification sent!', {
      headers: {
        'Content-Type': 'text/plain'
      }
    });
  } else {
    return new Response('Failed to send Slack notification', {
      status: response.status,
      headers: {
        'Content-Type': 'text/plain'
      }
    });
  }
}
721 chars
28 lines

In this example, the function sends a message with the text "Hello from Cloudflare Workers!" to the Slack webhook URL.

  1. A Cloudflare Worker that triggers the function. Here's an example Worker that triggers the function for a specific route:
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  if (request.method === 'POST' && request.url.endsWith('/send-slack-notification')) {  // replace this URL with your desired endpoint URL
    return sendSlackNotification(request);
  } else {
    return new Response('Invalid request', {
      status: 400,
      headers: {
        'Content-Type': 'text/plain'
      }
    });
  }
}
464 chars
17 lines

In this example, the sendSlackNotification() function is triggered when a POST request is made to the /send-slack-notification endpoint. You'll need to replace this URL with your desired endpoint URL.

With these three things in place, you should be able to send Slack notifications using Cloudflare Workers and JavaScript!

gistlibby LogSnag