CircleCI notification orbs were built to deliver messages to the appropriate channels when a build is successful or when it fails. This helps everyone involved in a project stay up-to-date with the status of the latest build.

In this tutorial, we will explore and implement notifications sent to a Slack channel and also sent via SMS. To accomplish this task, we will make use of the Slack and Twilio orbs from the CircleCI orb registry. This would be a cumbersome feature to implement from scratch, but with orbs we can achieve this in just a few lines of code.

Prerequisites

You need the following for this tutorial:

Getting started

First we will build a Nest.js application that returns a simple message. Then we will write a test to assert that the application returns the appropriate message. Afterwards, we will push our code to GitHub which will trigger the build on CircleCI. Once the build is successful, a custom message will be sent as an SMS to a preferred phone number and a specified Slack channel. This same process will be repeated in case the build fails. To begin, run the following command to create a new Nest.js application:

nest new nest-build-notifications

Go to the newly created project and run the application:

// change directory
cd nest-build-notifications

// run the application
npm run start:dev

Navigate to http://localhost:3000 to view the default homepage.

Homepage

This process returned a Hello World! message, which will suffice for our usecase in this tutorial.

Running the test locally

By default, a Nest.js application comes with a built-in testing framework (Jest) to provide assert functions. Also, a test script file located at src/app.controller.spec.ts has been written out-of-the-box to confirm that Hello World! was returned from the application. Use the following command to run the test:

npm run test

You will see output similar to what is below.

> nest-build-notifications@0.0.1 test /Users/yemiwebby/tutorial/circleci/nest-build-notifications
> jest

 PASS  src/app.controller.spec.ts
  AppController
    root
      ✓ should return "Hello World!" (10ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.55s, estimated 3s
Ran all test suites.

The test passes, which is enough for us to proceed with the tutorial.

Test passes

Adding CircleCI configuration to automate the test

Let’s add the configuration file to set up continuous integration with CircleCI. Create a folder named .circleci at the root of the application and create a new file named config.yml within it. Paste the following code into the new file (.circleci/config.yml):

version: 2.1
orbs:
  node: circleci/node@3.0.0
jobs:
  build-test-and-notify:
    executor:
      name: node/default
    steps:
      - checkout
      - run:
          name: Install dependencies
          command: npm install
      - run: npm test
workflows:
  build-and-notify:
    jobs:
      - build-test-and-notify

In the config file above, we have specified the Node.js orb version to be used from the CircleCI orbs registry and installed all the dependencies for our project. We then set up the command to run the test for our application.

Creating a GitHub repository

First, log in to your GitHub account and create a repository that will house this project.

Create repository

Then, navigate to the project directory from the terminal. Initialize the project with Git:

git init

Now, commit all your changes, add the remote repository, and push the project to GitHub with:

git add .
git commit -m "Initial commit"
git remote add origin https://github.com/<YOUR_USERNAME>/<YOUR_PROJECT_NAME>
git push -u origin master

Make sure to replace the YOUR_USERNAME and YOUR_PROJECT_NAME placeholders with your GitHub username and project name accordingly.

Setting up the project on CircleCI

Now that we have successfully created our project, installed all of its dependencies, and set up the configuration to automatically run the test once we push our code to GitHub, we now need to connect the project to CircleCI. To do that, log in to CircleCI with your account details and select the organization on GitHub where your project was pushed.

Select organisation

In this case, the name of our project is nest-build-notifications. Locate it using the name of the project as you have defined it on GitHub and click Set Up Project.

Setup project

This will take you to a different page where the configuration file for our project has been retrieved by CircleCI. Go ahead and click Start Building to proceed.

Start building

You will see a prompt with an option to continue with the setup process. For this tutorial, click Add Manually.

Add manually

On the next prompt, click Start Building thereby completing the setup.

Added configuration

This will immediately trigger the pipeline using the configuration in our project.

Pipeline running

And, you will get a successful build.

Pipeline success

Build details

Great! It worked as expected. Now, let’s start working on notifications that will indicate the status of our build process.

Adding Slack integration

To carry out this integration, I have created a workspace on Slack named CircleCI-Demo. You are allowed to use your preferred name but please note that you don’t necessarily have to create a new workspace for this purpose.

Slack workspace

Adding the CircleCI app

Once you have a workspace in place, open it and select the Apps link from the sidebar. This will show you a page with the list of Apps that can be integrated with your workspace for you and your team. Proceed to use the search input field to search the App Directory for CircleCI. Click Add.

Select Apps

Next, click Add to Slack.

Add to Slack

Select a channel where you want CircleCI notifications to be posted.

Add CircleCI integration

Finally, scroll down to the Webhook URL section on the page and copy the Webhook URL. Save it because it will be required later in the tutorial.

WebHook URL

Once you click Save Integration, you will see a message similar to the one below on the channel that you have selected during the setup.

Slack Channel message

Adding webhooks and other Slack details for the app

Navigate back to the CircleCI console on your browser. To enable notifications in your Slack workplace for this project, click Project Settings (at the top right corner of the pipelines page).

Project Settings

Next, click Slack Integration in the side menu.

Slack integration page

Click Add Webhook URL. You will see a prompt with an input field for you to enter the Webhook URL copied earlier.

Add webhook

Paste the webhook URL in the field and click Save to proceed.

Update the CircleCI configuration

To complete the steps required for integrating Slack, you need to update the CircleCI configuration file to include the CircleCI orb for Slack. Open .circleci/config.yml and update its content as shown here:

version: 2.1
orbs:
  node: circleci/node@3.0.0
  slack: circleci/slack@3.4.2
jobs:
  build-test-and-notify:
    executor:
      name: node/default
    steps:
      - checkout
      - run:
          name: Install dependencies
          command: npm install
      - run: npm test
      - slack/notify:
          color: "#42e2f4"
          mentions: "yemiwebby,"
          message: A custom message to notify the channel about the latest build
      - slack/status:
          fail_only: true
          mentions: "yemiwebby"
workflows:
  build-and-notify:
    jobs:
      - build-test-and-notify

In the file above, we included another orb in the pipeline for our Slack integration. Two new commands were also added:

  • slack/notify: Send a custom message at any point in a job
  • slack/status: Send a message only when there is an error during the build process

These are all the updates required for us to have custom messages sent to a Slack workspace to track the status of our build on CircleCI. Remember to update the mentions among other values as you see fit. Before updating the repository with the latest code, we also need to integrate with Twilio for SMS notifications.

Integrating with Twilio for Notifications

In this section, we will take notifications for our CircleCI build a step further by integrating it with Twilio. As mentioned earlier, the CircleCI orbs registry already has a Twilio orb for sending custom SMS notifications for a CircleCI job.

To integrate with Twilio, you will need the following:

  • TWILIO_FROM: This must be a Twilio phone number that you own, formatted with a + and country code, e.g. +16175551212 (E.164 format)
  • TWILIO_TO: This parameter determines the destination phone number for your SMS message and requires the same format as above
  • TWILIO_SID: This is your Twilio Account SID that can be obtained from your Twilio account dashboard
  • TWILIO_TOKEN: This is your Twilio AUTH TOKEN
  • body: A custom message that will be displayed instead of the default notification messages

Adding environment variables on CircleCI

Obtain all the credentials mentioned in the previous section from your Twilio account dashboard and navigate back to the project settings page on CircleCI. Once opened, click Environment Variables on the side menu. Then click Add Variable and input your Twilio credentials as shown here.

Environment Variables

Navigate back to the project settings page once you are done.

Update the CircleCI configuration file

Now, we need to update the CircleCI configuration file with the CircleCI Twilio orb details and the required commands. Open the .circleci/config.yml file and update its content as shown below:

version: 2.1
orbs:
  node: circleci/node@3.0.0
  slack: circleci/slack@3.4.2
  twilio: circleci/twilio@0.0.1
jobs:
  build-test-and-notify:
    executor:
      name: node/default
    steps:
      - checkout
      - run:
          name: Install dependencies
          command: npm install
      - run: npm test
      - slack/notify:
          color: "#42e2f4"
          mentions: "yemiwebby,"
          message: A custom message to notify the channel about the latest build
      - slack/status:
          fail_only: true
          mentions: "yemiwebby"
      - twilio/sendsms:
          body: Send SMS to twilio
      - twilio/alert:
          body: Send SMS for error
workflows:
  build-and-notify:
    jobs:
      - build-test-and-notify

We made changes to this file by including the Twilio orb and the following commands:

  • twilio/sendsms: This command will be used to send SMS once the build is successful
  • twilio/alert: This command will only be triggered to send SMS once an error occurs during the build

Updating the AppController

Make some changes to the AppController by updating the content of src/app.controller.ts file as shown here:

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}
  @Get()
  getHello(): string {
    return this.appService.getHello();
  }

  // add this
  @Get('/message')
  getMessage(): string {
    return 'This is a sample message';
  }
}

Testing for a successful build

Commit all the code changes and push them to GitHub. This will automatically trigger the build on the CircleCI console. Once the process is completed and built successfully, you will receive the custom messages on the channel specified for your Slack workspace and also via SMS.

In my case, here is the message on the #general channel of the CircleCI-Demo workspace.

Slack custom message

Here’s the SMS from Twilio.

Twilio custom message

Testing for a fail build

To make the build on CircleCI fail for this project, open src/app.service.ts file and update the return message as shown below:

import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
  getHello(): string {
    return 'Sample message';
  }
}

Here, we altered the message so that our test will fail. Now, add all the new changes, commit them, and push them to GitHub. This will again trigger the build, which will fail this time around. Once that is done, you will receive a message as expected both on Slack and Twilio as depicted by the images below.

Slack error message

Twilio error message

Conclusion

The best thing about what we learned in this tutorial is that implementing these notification features is so simple and seamless, and they can be easily integrated into any of your existing projects.

Also, bear in mind that this is not limited to Node.js application. You can easily transfer and use the knowledge gained here to other projects regardless of the framework or programming language used. Check the CircleCI orbs registry to learn more about other awesome packages.

The complete source code can be found here on GitHub.


Oluyemi is a tech enthusiast, programming freak, and a web development junkie who loves to embrace new technology.