Send Slack Notifications via NodeJS
Hrishikesh Sharma
Posted on July 9, 2023
Slack has always been a leading project management tool used by project developers, managers and founders.
While working on a project, it is very useful to setup a common notifier system for a number of key reasons:
- One wants to be notified when a new user signs up 🚀
- One wants to be alerted when a user was trying to complete an action and they encounters error 😑
- One wants to be alerted when a user pays up for any in-app purchases, subscriptions etc. 💸
With these notifications in place, it helps to keep the team notified so that everyone is on the same page!
Let's setup the 'Slack App' first:
Go to Slack API Page and click the "Create New App" button.
Select 'From scratch' and provide a name of your app and then choose the desired workspace.
Under Basic Information section, under “Add features and functionality” section, click on “Permissions” tab, you will be redirected to "OAuth & Permissions" page under which scroll to "Scopes" section, and select the permissions shown in the screenshot below:
Once those permissions have been added, scroll up to fetch the OAuth token which will be later used in the app for sending the notifications.
Note: OAuth token is provided after the app has been installed on your workspace (the one which you selected while creating the app.)
Clicking on the "Install to workspace" button, you'll see the page below, kindly Allow the installation.
After allowing to app to install, you'll be redirected back to the same page and this time, oauth token will be visible now.
Copy the OAuth token and next we'll fetch the channel id, under slack, open the channel and click on the channel name and you'll see the popup shown below,
Now let's setup the Node app now..
Create a node app or use an existing one and run npm i @slack/web-api
in order to install the slack client for nodejs.
Create another file under utils folder by the name slack.util.js
.
Then, define the SLACK_TOKEN
&& SLACK_CHANNEL_ID
in your .env
file.
Now, run the code, and while running, if you see the error below, then it is because we have to make the app join the channel as well.
So in order to make user join the channel, check the snippet below,
const resp = await web.conversations.join({
channel: channel,
});
if (message) {
await sendSlackMessage(message, channel);
}
After using the code above, lets trigger the notification and voila!
The full code is available for your reference here.
Further, you can create an API to fetch the active channels from slack and then make channel selection dynamic directly from your app. Let me know if you have some questions.
Thanks!
Posted on July 9, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.