Monday, July 25, 2022
HomeWordPress DevelopmentCreate a notifications system utilizing in-app (bell icon) and emails

Create a notifications system utilizing in-app (bell icon) and emails


On this article, I’ll information you thru sending notifications in-app and by way of electronic mail utilizing Novu in a Node.js software. We’ll first create a Novu challenge, add an electronic mail communication channel by way of the Novu Handle Platform, set up Novu to an Categorical app, and ship in-app and electronic mail messages utilizing Novu 🚀.

You need to implement product notifications on your customers for instance, in-app notifications (just like the bell icon you have got on fb), ship an electronic mail / sms or push notification in a movement.

A fast instance may be: Fb is sending you a notification into your bell icon (You’ve a brand new pal request) and after 1 hour you have not learn it, they ship you an electronic mail.

Novu is the primary open-source notification infrastructure that manages all types of communication from electronic mail to SMS, Push notifications, and many others.
https://github.com/novuhq/novu

It allows you to add a number of emails and SMS communication channels, create shared message templates, monitor each exercise, and change between totally different communication channels of your alternative.



Central communication system

One of many the explanation why Novu stands out is the flexibility to have a central technique of communication. Novu gives a dashboard the place you may monitor and handle all of your SMS and electronic mail communications. With Novu, you may simply observe communication by way of a number of channels on a single dashboard.



A number of communication channels can be found

With Novu, you should utilize as many communication channels as doable and simply change from one to a different with out modifying the present code in your software.
For example, if you happen to use Sendgrid to ship emails in your internet software, however the service turns into unavailable for a second, you may change to different communication channels till Sendgrid is offered with out altering your code. Novu makes communication together with your customers simple to make use of and preserve.



Content material administration system

Novu gives each consumer with a content material administration system the place you may create reusable electronic mail and SMS templates you can share throughout varied software program functions. With Novu, you needn’t fear in regards to the stress of making dynamic content material. Novu makes use of handlebars templating engine to just accept dynamic variables, thus, creating a singular expertise on your customers.



Open supply software program

Novu is open-source software program; which means the code is available for everybody to switch and enhance. Novu has a big neighborhood of builders and proficient contributors consistently sustaining and bettering the software program. As a consumer, you may be certain of getting the perfect efficiency while you use Novu. You can too request adjustments to the documentation, ask for assist, and chat with the maintainers while you need assistance or encounter errors.

BTW: You may change into a contributor and get acknowledged! We have now created a particular web page for all our contributors with recognition for his or her tremendous laborious work, and badges they’ll implement on their Github 🚀
Seize a brand new subject right here: https://novu.co/contributors
Image description

Right here, I’ll information you thru making a Novu challenge and organising Novu for sending emails and in-app notifications.

Create your challenge folder and open the folder.

mkdir <folder_name>
cd <folder_name>
Enter fullscreen mode

Exit fullscreen mode

Guarantee you have got Node.js put in in your laptop, then run the code snippet under in your terminal to create a Novu challenge.

npx novu init
Enter fullscreen mode

Exit fullscreen mode

You have to to sign up with Github earlier than making a Novu challenge. The code snippet under accommodates the steps it’s best to observe after working npx novu init.

Now let's setup your account and ship your first notification
❓ What's your software title? <Your_application_name>
❓ Now lets setup your setting. How would you wish to proceed? 
   > Create a free cloud account (Beneficial)
   Create your account with: Signal-in with GitHub
✔️ Create your account efficiently.

Now let's setup your account and ship your first notification
❓ Seems like you have already got a created an account for Growth (Use arrow keys)
> Go to Growth Dashboard
  Cancel
Enter fullscreen mode

Exit fullscreen mode

The code snippet above opens the Novu Handle Platform in your default browser.

Novu Dashboard page

Novu Dashboard web page

Congratulations 🎊, you’ve got efficiently created an account with Novu. Subsequent, click on the Configure Now button so as to add an E-mail supplier. I shall be utilizing Sendgrid on this article.



Methods to add Sendgrid electronic mail supplier to Novu

I’ve choosen Sendgrid however you may simply select certainly one of: Mailgun, SES, Postmark, NodeMailer, Mailjet, Mandrill, SendinBlue, and EmailJS.

In case you are lacking a supplier, simply open a brand new subject on Github 🙂

Let’s arrange a brand new Sendgrid account and add it to Novu.

Open one other tab, go to the Twilio Sendgrid web site and create an account utilizing a piece or firm electronic mail.

Register, click on Settings in your sidebar, and choose API Keys to create a SendGrid API key with full entry to “Mail Ship” permissions.

Copy the API key, and paste it into the Novu Handle Platform

Novu Sendgrid.png

Click on the settings icon beside Twilio Sendgrid within the picture above and paste the API Key into the API Key discipline.

Novu API field.png

Return to your Sendgrid dashboard to create and confirm a Sender Identification.

Paste the e-mail deal with and the sender title into their fields within the picture above, guarantee it’s energetic and click on the Replace button.

Congratulations 🎊, you have got efficiently related your Sendgrid account to Novu, and you can begin sending emails by way of Novu.

Subsequent, let’s create a workflow displaying how we need to ship notifications in our Node.js software.



Methods to create a Novu notification workflow

Click on Notifications from the sidebar and choose the Notification template already created for you by default.

Choose Workflow Editor to create the notification workflow, then drag the totally different notification channels out of your right-hand aspect into the massive field within the heart of the web page.

Novu workflow.png

Make sure the workflow is identical because the picture above and click on the Replace button to avoid wasting the steps.

Subsequent, let’s create an Categorical app and add Novu to the Node.js software.



Including Novu to an Categorical software

On this part, you will learn to arrange an Categorical Node.js server and add Novu to the appliance.

Within the challenge’s folder created within the earlier part, create a bundle.json file and an index.js file – the entry level to the Node.js software.

cd <project-folder>
npm init -y & contact index.js
Enter fullscreen mode

Exit fullscreen mode

Set up Categorical and Novu SDK for Node.js. Categorical.js is a quick, minimalist framework that gives a number of options for constructing internet functions in Node.js.

npm set up specific @novu/node
Enter fullscreen mode

Exit fullscreen mode

Copy and paste the code snippet under into the index.js file to create an Categorical software.

const specific = require('specific'); //import expressjs
const app = specific();
const PORT = 4000; // the place the server runs
const path = require('path');

//permits entry to information despatched from the shopper - index.html file
app.use(specific.urlencoded({ prolonged: true }));

//creates a route that shows an index.html file.
app.get('/', (req, res) => {
  res.sendFile(path.be part of(__dirname, '/index.html'));
});

//listens to updates made on the challenge and exhibits the standing of the challenge
app.pay attention(PORT, () => {
  console.log(`⚡️[server]: Server is working at https://localhost:${PORT}`);
});
Enter fullscreen mode

Exit fullscreen mode

Create the index.html file referenced above and replica the code under into the file.

<!DOCTYPE html>
<head>
  <title>Producing Employment Letter</title>
  <hyperlink rel="preconnect" href="https://fonts.googleapis.com">
<hyperlink rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<hyperlink href="https://fonts.googleapis.com/css2?household=Poppins:wght@100;200;300;400;500;600;700;800;900&show=swap" rel="stylesheet">
  <model>
    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
      font-family: 'Poppins', sans-serif;
    }
    type {
      min-height: 100vh;
      width: 100%;
      padding: 30px;
      show: flex;
      align-items: heart;
      justify-content: heart;
      flex-direction: column;
    }
    enter {
      padding: 10px;
      width: 100%;
      define: none;
      border: 1px strong #ddd;
      border-radius: 3px;
      margin-bottom: 20px;
    }
    #button {
      width: 200px;
      padding: 20px;
      define: none;
      border: none;
      background-color: #333;
      shade: #fff;
      cursor: pointer;
      margin-top: 30px;
      border-radius: 3px;
    }
    h2 {
      margin-bottom: 20px;
    }
    .container {
      show: flex;
      width: 100%;
      align-items: heart;
      justify-content: space-between;
    }
    .container div {
      width: 45%;
    }
    #personnel {
      margin-top: 30px;
    }
    #others div {
      width: 30%;
    }

  </model>
</head>
<physique>
    <type technique="POST" motion="/despatched">
      <h2>Candidate's info</h2>
      <div class="container">
          <div>
            <label for="candidateFirstName">Candidate's First Identify</label>
            <enter sort="textual content" title="candidateFirstName" id="candidateFirstName"/>
          </div>

          <div>
            <label for="candidateLastName">Candidate's Final Identify</label>
            <enter sort="textual content" title="candidateLastName" id="candidateLastName"/>
          </div>
      </div>

      <div class="container" id="others">
          <div>
            <label for="candidateEmail" >Candidate's E-mail</label>
            <enter sort="electronic mail" title="candidateEmail" id="candidateEmail"/>
          </div>

          <div>
            <label for="candidateSalary" >Proposed Wage</label>
            <enter sort="quantity" title="candidateSalary" id="candidateSalary"/>
          </div>

          <div>
            <label for="candidatePosition" >Proposed Place</label>
            <enter sort="textual content" title="candidatePosition" id="candidatePosition"/>
          </div>
      </div>

      <h2 id="personnel">Official Personnel</h2>

        <div class="container">
            <div>
              <label for="officialFullName" >Full Identify</label>
              <enter sort="textual content" title="officialFullName" id="officialFullName"/>
            </div>
            <div>
              <label for="officialPosition" >Place Held</label>
              <enter sort="textual content" title="officialPosition" id="officialPosition"/>
            </div>
        </div>

        <button id="button">SEND OFFER</button>
    </type>
</physique>
</html>
Enter fullscreen mode

Exit fullscreen mode

Run the index.js file by copying the code under. Go to http://localhost:4000 to view the index.html file.

node index.js
Enter fullscreen mode

Exit fullscreen mode

Subsequent, I’ll present you easy methods to ship emails and in-app notifications by way of Novu by creating an online software that generates provide letters for profitable job candidates in a company. The index.html file is the net shopper/structure of the appliance.



Methods to ship electronic mail notifications utilizing Novu

Right here, I’ll information you thru creating electronic mail templates and sending them to customers by way of Novu.

Go to the Novu Handle Platform, choose the Notification template, and click on on Workflow Editor.

Choose E-mail from the massive heart field to edit the template.

Novu edit template.png

Novu permits us so as to add plain textual content and customized code utilizing HTML templates with the Handlebars templating engine as electronic mail content material.

Copy and paste this because the Topic line of the e-mail

OFFER LETTER FROM NOVU - CONGRATULATIONS {{candidateFirstName}}
Enter fullscreen mode

Exit fullscreen mode

Choose Customized Code because the content material sort and replica the code under. The e-mail content material and the topic line enable us to cross dynamic information into the variables utilizing the Handlebars templating engine.

<physique>
  <p>Pricey {{candidateFirstName}} {{candidateLastName}}</p>
  <p>That is to tell you that you have been supplied a place at Novu as a
    {{candidatePosition}}
    with a beginning wage of
    {{candidateSalary}}
  </p>
  <p>Kindly signal the connected doc.</p>
  <p>Congratulations, as soon as once more</p>
  <br />
  <p>{{officialFullName}} </p>
  <p><em>{{officialPosition}}</em></p>
</physique>
Enter fullscreen mode

Exit fullscreen mode

Now you can save the template. Subsequent, let me stroll you thru sending this template by way of electronic mail.

Import Novu into the index.js file. To get your API key, click on on Settings on the Novu Handle Platform, choose API Keys, and replica it into the code under.

//Import and instantiate Novu within the index.js file

const { Novu } = require('@novu/node');
const novu = new Novu(<YOUR_API_KEY>);
Enter fullscreen mode

Exit fullscreen mode

Create a despatched route that accepts solely POST requests within the index.js file, and replica the code under. This route receives all of the consumer’s information from the shopper and logs them to the console.

app.put up('/despatched', (req, res) => {
  //Will get the inputs from the net shopper
  const {
    officialPosition,
    officialFullName,
    candidateEmail,
    candidateSalary,
    candidatePosition,
    candidateFirstName,
    candidateLastName,
  } = req.physique;

  //Logs the information to the shopper
  console.log({
    officialPosition,
    officialFullName,
    candidateEmail,
    candidateSalary,
    candidatePosition,
    candidateFirstName,
    candidateLastName,
  });
});
Enter fullscreen mode

Exit fullscreen mode

As soon as you’ve got retrieved the information from the shopper, replace the POST path to ship the e-mail to the appliance utilizing the Novu template.

app.put up('/despatched', async (req, res) => {
  const {
    officialPosition,
    officialFullName,
    candidateEmail,
    candidateSalary,
    candidatePosition,
    candidateFirstName,
    candidateLastName,
  } = req.physique;

  await novu
    .set off('on-boarding-notification', {
      to: {
        subscriberId: '<YOUR SUBSCRIBER_ID>',
        electronic mail: candidateEmail,
      },
      payload: {
        officialPosition,
        officialFullName,
        candidateSalary,
        candidatePosition,
        candidateFirstName,
        candidateLastName,
      },
    })
    .then((information) => {
      console.log(information);
    })
    .catch((err) => console.error(err));

  // redirects to the despatched.html file
  res.sendFile(path.be part of(__dirname, '/despatched.html'));
});
Enter fullscreen mode

Exit fullscreen mode

In response to the code snippet above, I modified the callback perform to an asynchronous one earlier than including Novu. Novu then triggers the e-mail templates by way of its ID and sends the template to the candidate’s electronic mail. The payload object accommodates all of the dynamic information required by the template.

To get your Subscriber ID, click on on Settings on the Novu Handle Platform, and replica and paste the Utility Identifier.

Create the despatched.html file referenced within the code snippet above.

<!DOCTYPE html>
  <head>
    <title>E-mail Despatched!</title>
  </head>
  <physique>
    <p> Message despatched!</p>
  </physique>
</html>
Enter fullscreen mode

Exit fullscreen mode

Begin the Node.js server by working the code under.

node index.js
Enter fullscreen mode

Exit fullscreen mode

So as to add attachments to the e-mail messages, you may create an attachments array throughout the payload object or add the doc by way of the Novu Handle Platform.

await novu
    .set off('on-boarding-notification', {
      to: {
        subscriberId: '<YOUR SUBSCRIBER_ID>',
        electronic mail: candidateEmail,
      },
      payload: {
        ...,
        attachments: [
          {
            file: fs.readFileSync(__dirname + '/test.jpeg'),
            name: 'test.jpeg',
            mime: 'image/jpg',
          },
      ],
      },
    })
    .then((information) => {
      console.log(information);
    }).catch((err) => console.error(err));
Enter fullscreen mode

Exit fullscreen mode

The code snippet above attaches a picture to the e-mail earlier than sending the e-mail to the recipient. Subsequent, let’s learn to ship in-app notifications to the net shopper.



Methods to ship in-app notifications utilizing Novu

On this part, you will learn to ship in-app notifications and show them on the net shopper of your software.

Go to the Novu Handle Platform, choose the template you might be utilizing, and click on on Workflow Editor.

Choose In-app from the massive heart field, click on the Edit Template button to edit the notification and save the content material.

Novu in-app notification.png

Replace the despatched.html file to comprise the JavaScript code and the bell icon earlier than its closing physique tag. The JavaScript code shows the in-app notification bar when a consumer clicks the bell icon.

<!DOCTYPE html>
<head>
    <title>Despatched!</title>
    <!-- FontAwesome CDN hyperlink-->
    <script src="https://equipment.fontawesome.com/0c7ff73f65.js" crossorigin="nameless"></script>
</head>

<physique>
    <p> Message despatched!</p>

    <!-- The components Novu wants to show the Notification bar -->
    <div id="notification-bell" model="min-height: 300px; width: 100%">
        <i class="fa fa-bell"></i>
        <span id="unseen-badge"></span>
    </div>

    <script sort="module">
        (perform(n,o,t,i,f, m) {
          n[i] = {}, m = ['init']; n[i]._c = [];m.forEach(me => n[i][me] = perform() {n[i]._c.push([me, arguments])});
          var elt = o.createElement(f); elt.sort = "textual content/javascript"; elt.async = true; elt.src = t;
          var earlier than = o.getElementsByTagName(f)[0]; earlier than.parentNode.insertBefore(elt, earlier than);
        })(window, doc, 'https://embed.novu.co/embed.umd.min.js', 'novu', 'script');

        novu.init('Xr_knh-UYIPD', '#notification-bell', {
          subscriberId: "Xr_knh-UYIPD",
          electronic mail: "nevo@novu.co",
          firstName: "Nevo",
          lastName: "David",
        });
      </script>
</physique>
</html>
Enter fullscreen mode

Exit fullscreen mode

NB: You may get the bell icon from Font Superior and make sure the CSS id referenced within the JavaScript code exists in your HTML file.

Novu in-app notification bar.png



Supply Code

You may test the whole supply code right here:
https://github.com/novuhq/weblog/tree/predominant/sendingpercent20notificationspercent20withpercent20Novu
That is simply the specific server to work together with Novu.
Earlier than you clone the challenge, please run.

npx novu init
Enter fullscreen mode

Exit fullscreen mode



Conclusion

On this tutorial, you’ve got learnt what Novu is, why it’s best to use it, easy methods to create a Novu challenge, easy methods to add Novu to an Categorical.js internet software, and easy methods to ship emails and in-app notifications with Novu.

Novu makes it simple so that you can ship, monitor, and handle notifications by way of varied SMS and E-mail communication channels. It allows you to create a wealthy notification system in your functions, thereby offering an awesome consumer expertise on your customers.

You can too be part of the neighborhood to contribute, chat with the maintainers and enhance the software program.

Thanks for studying!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments