Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?

Building an In-App Bell Notification in React using Novu

Cover image by storyset on Freepik

Push notifications usually are not seen pretty much as good observe. They distract you, need your consideration or generally they’re too frequent. However, In-app notifications are extra helpful and might replace you in regards to the utility.

Novu is an open-source notification administration device. They supply E mail, SMS, Push, and In-App notification. E mail and SMS notifications are depending on suppliers. They’ve suppliers reminiscent of Sendinblue for e-mail and Twilio for SMS. There are different suppliers too.

So, in the present day, we’re going to use the In-App notification function of Novu to setup the next:

  • Making a set off in Novu Dashboard
  • Constructing Bell Icon utilizing Notification Middle
  • Initiating set off in Node utilizing Categorical

Let’s get began.

Since its an internet utility undertaking, I hope you understand the next:

  • Net Growth with HTML, CSS, and JavaScript
  • Fundamental React

As for the instruments, we have to have these instruments pre-installed.

  • Node: It supplies you with a JavaScript runtime surroundings. It would assist set up dependencies and run scripts.

Go to novu.co and click on on GET STARTED to create a Novu account. After creating the account, the Novu dashboard will open.

From the Notifications panel, Click on on + New to create a notification template. From Create new template, Enter the Notification Title. Choose Workflow Editor so as to add an In-App notification. Drag and drop the In-App steps from Steps so as to add to the Workflow editor.

Now, Click on on the In-App step from the Workflow Editor to open its properties in the proper panel. Click on on Edit Template from that menu so as to add message content material to the notification. Add your message and you can too add a button to the notification.

Novu - Edit Notificaiton Template

After including the message content material and URL, Click on on Create to create the notification. A message can be pop-up with code to initialize the set off. A set off in Novu is a perform that may begin the sending of notifications. Click on on Acquired it to proceed.

Now, its time to put in writing some code.

The undertaking goes to have a frontend in React. Within the frontend, we’ll construct our bell icon and its function utilizing the notification heart of Novu. The set off for initializing the notification must be in Node. That is why we’re going to use ExpressJS for our node server. For exchanging knowledge, we’re going to use the API. Now, let’s create the undertaking/

Set up a React undertaking with the beneath command within the terminal.

npx create-react-app novu-inapp
Enter fullscreen mode

Exit fullscreen mode

Take away the pointless file and code.

We’re going to want the next dependencies on our frontend:

  • notificaiton-center: That is by Novu to handle the In-App notification. I will even present us with the UI for the bell and notification panel.

  • axios: This can be useful in making request to our Node server in Categorical.

You’ll be able to set up all of the above dependencies with the beneath command:

npm i @novu/notification-center axios
Enter fullscreen mode

Exit fullscreen mode



App.js

In App.js, we’re going to construct our UI and make a request to our backend server for initializing the notification. Right here is the code.

import "./App.css";
import { useState } from "react";
import NovuBell from "./part/NovuBell";
import axios from "axios";

perform App() {
  const [status, setStatus] = useState(); // standing of handed/failed notificaiton

  const sendNotification = async () => {
    await axios
      .publish("http://localhost:8000", {
        subscriberId: `${course of.env.REACT_APP_SUBSCRIBER_ID}`,
      })
      .then((res) => {
        setStatus(res.standing);
      });
  };

  return (
    <div className="App">
      <div className="NavBar">
        <h1>Notificaiton by Novu</h1>
        <NovuBell subscriberId={course of.env.REACT_APP_SUBSCRIBER_ID} />
      </div>
      <button onClick={sendNotification}>Ship Notification</button>
      {standing === 201 && <h1>Notification Despatched</h1>}
      {standing === 400 && <h1>Notification could not despatched</h1>}
    </div>
  );
}

export default App;

Enter fullscreen mode

Exit fullscreen mode

As you’ll be able to see, we’re having a Ship Notification button. It will name the sendNotificaiton perform. This perform will make a name to our server with the subscriberId. A subscriberId is a singular string. Novu is utilizing it to determine the receiver of the notification. In a database, it may be the userId which you could fetch and cross because the parameter. Now we have applied this as the environment for our utility (You should not do this, I’m doing this for testing functions solely).



.env

Because the surroundings variable, we’re going to want Novu API and utility identifier. You may get it out of your Novu Dashboard. Navigate to Setting -> API keys.

Novu - Settings

Create a .env file within the root listing so as to add the API key and utility identifier. Together with this, we’re additionally going so as to add the subscriberId. This may be any random distinctive string.

REACT_APP_NOVU_API=<API KEY>
REACT_APP_NOVU_IDENTIFIER=<APPLICATION IDENTIFIER>
REACT_APP_SUBSCRIBER_ID=<SUBSCRIBER ID>
Enter fullscreen mode

Exit fullscreen mode



Notification Part

Now, it is time to create our bell notification. Create a part folder within the src folder. Inside it creates a file with the title NovuBell.js

Right here is the code for the notification bell.

import {
  NovuProvider,
  PopoverNotificationCenter,
  NotificationBell,
} from "@novu/notification-center";

perform NovuBell({}) {
  return (
    <NovuProvider
      subscriberId={course of.env.REACT_APP_SUBSCRIBER_ID}
      applicationIdentifier={course of.env.REACT_APP_NOVU_IDENTIFIER}
    >
      <PopoverNotificationCenter>
        {({ unseenCount }) => <NotificationBell unseenCount={unseenCount} />}
      </PopoverNotificationCenter>
    </NovuProvider>
  );
}

export default NovuBell;

Enter fullscreen mode

Exit fullscreen mode

Now it is time to create our server. Within the root listing create a file with the title server.js.

We’re going to want the next dependencies for our node server:

  • express: It is a framework to create our backend.

  • @novu/node: It’s a library for accessing the function of novu in node. We’re going to use this for initializing the notification.

  • cors: For dealing with cors-related errors.

  • [dotenv]: For accessing the surroundings variable in our node server.

You’ll be able to set up all of the above dependencies with the beneath command:

npm i categorical cors dotenv
Enter fullscreen mode

Exit fullscreen mode

Right here is the code for the server.js:

const { Novu } = require("@novu/node");
const categorical = require("categorical");
const cors = require("cors");
require("dotenv").config();

const app = categorical();

const novu = new Novu(course of.env.REACT_APP_NOVU_API);

app.use(cors());
app.use(categorical.json({ prolonged: false }));

app.publish("/", async (req, res) => {
  attempt {
    const { standing } = await novu.set off("bell-notification", {
      to: {
        subscriberId: req.physique.subscriberId,
      },
      payload: {},
    });
    res.ship(standing);
  } catch (err) {
    console.log(err);
  }
});

const PORT = course of.env.PORT || 8000;

app.pay attention(PORT, () => console.log(`Server began at ${PORT}`));

Enter fullscreen mode

Exit fullscreen mode

Within the try-catch block, we’re initiating the bell-notification template. It’s being initiated by novu.set off. In to, we’re sending the subscriberId of the receiver. You’ll be able to cross extra knowledge reminiscent of title within the payload.

We’re sending again the standing of the decision reminiscent of 401 and 200 to our frontend. On this standing foundation, we’re going the resolve whether or not the notification is efficiently despatched or not.

Run the server with the beneath command:

node server.js
Enter fullscreen mode

Exit fullscreen mode

It ought to print “Server began at 8000” within the console.

Run the React with the beneath command:

npm run begin
Enter fullscreen mode

Exit fullscreen mode

It would run the React at http://localhost:3000/. It ought to appear like this:

Localhost - Notificaiton by Novu

Now, if you happen to click on on the Ship Notificaiton button a notification can be despatched. As our fronted will obtain the notification. The bell icon will change to indicate the notification. Click on on the bell icon to entry the notification.

Bell Notificaiton

Now we have constructed the notification bell utilizing the Novu. You’ll be able to add a button to this notification to redirect the person as soon as they click on on it. You may encounter a couple of warnings within the console whereas operating React. It’s attributable to the ‘@novu/notification-center` library. I attempted to resolve it however could not discover any resolution. Should you discover one thing, do point out it within the remark.

Novu can give you many fascinating options of notification. You’ll be able to learn the Notification Center for React Component from their docs for including extra options to the prevailing undertaking.

I hope this information has supplied you with helpful details about Novu and its In-App notification. Thanks for studying the weblog publish.

Add a Comment

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?