javascript
Building an In-App Bell Notification in React using Novu
Cover image by storyset on Freepik
Introduction
Push notifications are not seen as good practice. They distract you, want your attention or sometimes they are too frequent. But, In-app notifications are more useful and can update you about the application.
Novu is an open-source notification management tool. They provide Email, SMS, Push, and In-App notification. Email and SMS notifications are dependent on providers. They have providers such as Sendinblue for email and Twilio for SMS. There are other providers too.
So, today, we are going to use the In-App notification feature of Novu to setup the following:
- Creating a trigger in Novu Dashboard
- Building Bell Icon using Notification Center
- Initiating trigger in Node using Express
Let's get started.
Prequisitise
Since its a web application project, I hope you know the following:
- Web Development with HTML, CSS, and JavaScript
- Basic React
As for the tools, we need to have these tools pre-installed.
- Node: It provides you with a JavaScript runtime environment. It will help install dependencies and run scripts.
Creating account and Setting up Novu Dahboard
Visit novu.co and click on GET STARTED
to create a Novu account. After creating the account, the Novu dashboard will open.
From the Notifications panel, Click on + New
to create a notification template. From Create new template
, Enter the Notification Name. Select Workflow Editor
to add an In-App notification. Drag and drop the In-App
steps from Steps to add
to the Workflow editor.
Now, Click on the In-App
step from the Workflow Editor to open its properties in the right panel. Click on Edit Template
from that menu to add message content to the notification. Add your message and you can also add a button to the notification.
After adding the message content and URL, Click on Create
to create the notification. A message will be pop-up with code to initialize the trigger. A trigger in Novu is a function that will start the sending of notifications. Click on Got it
to proceed.
Now, its time to write some code.
Bell Icon in React
The project is going to have a frontend in React. In the frontend, we will build our bell icon and its feature using the notification center of Novu. The trigger for initializing the notification has to be in Node. That's why we are going to use ExpressJS for our node server. For exchanging data, we are going to use the API. Now, let's create the project/
Install a React project with the below command in the terminal.
npx create-react-app novu-inapp
Remove the unnecessary file and code.
We are going to need the following dependencies on our frontend:
notificaiton-center: This is by Novu to manage the In-App notification. I will also provide us with the UI for the bell and notification panel.
axios: This will be helpful in making request to our Node server in Express.
You can install all the above dependencies with the below command:
npm i @novu/notification-center axios
App.js
In App.js, we are going to build our UI and make a request to our backend server for initializing the notification. Here is the code.
import "./App.css";
import { useState } from "react";
import NovuBell from "./component/NovuBell";
import axios from "axios";
function App() {
const [status, setStatus] = useState(); // status of passed/failed notificaiton
const sendNotification = async () => {
await axios
.post("http://localhost:8000", {
subscriberId: `${process.env.REACT_APP_SUBSCRIBER_ID}`,
})
.then((res) => {
setStatus(res.status);
});
};
return (
<div className="App">
<div className="NavBar">
<h1>Notificaiton by Novu</h1>
<NovuBell subscriberId={process.env.REACT_APP_SUBSCRIBER_ID} />
</div>
<button onClick={sendNotification}>Send Notification</button>
{status === 201 && <h1>Notification Sent</h1>}
{status === 400 && <h1>Notification couldn't sent</h1>}
</div>
);
}
export default App;
As you can see, we are having a Send Notification
button. This will call the sendNotificaiton
function. This function will make a call to our server with the subscriberId. A subscriberId is a unique string. Novu is using it to identify the receiver of the notification. In a database, it can be the userId that you can fetch and pass as the parameter. We have implemented this as our environment for our application (You shouldn't do that, I am doing this for testing purposes only).
.env
As the environment variable, we are going to need Novu API and application identifier. You can get it from your Novu Dashboard. Navigate to Setting -> API keys.
Create a .env
file in the root directory to add the API key and application identifier. Along with this, we are also going to add the subscriberId
. This can be any random unique string.
REACT_APP_NOVU_API=<API KEY>
REACT_APP_NOVU_IDENTIFIER=<APPLICATION IDENTIFIER>
REACT_APP_SUBSCRIBER_ID=<SUBSCRIBER ID>
Notification Component
Now, it's time to create our bell notification. Create a component
folder in the src
folder. Within it creates a file with the name NovuBell.js
Here is the code for the notification bell.
import {
NovuProvider,
PopoverNotificationCenter,
NotificationBell,
} from "@novu/notification-center";
function NovuBell({}) {
return (
<NovuProvider
subscriberId={process.env.REACT_APP_SUBSCRIBER_ID}
applicationIdentifier={process.env.REACT_APP_NOVU_IDENTIFIER}
>
<PopoverNotificationCenter>
{({ unseenCount }) => <NotificationBell unseenCount={unseenCount} />}
</PopoverNotificationCenter>
</NovuProvider>
);
}
export default NovuBell;
server.js
Now it's time to create our server. In the root directory create a file with the name server.js
.
We are going to need the following dependencies for our node server:
express: It's a framework to create our backend.
@novu/node: It is a library for accessing the feature of novu in node. We are going to use this for initializing the notification.
cors: For handling cors-related errors.
[dotenv]: For accessing the environment variable in our node server.
You can install all the above dependencies with the below command:
npm i express cors dotenv
Here is the code for the server.js
:
const { Novu } = require("@novu/node");
const express = require("express");
const cors = require("cors");
require("dotenv").config();
const app = express();
const novu = new Novu(process.env.REACT_APP_NOVU_API);
app.use(cors());
app.use(express.json({ extended: false }));
app.post("/", async (req, res) => {
try {
const { status } = await novu.trigger("bell-notification", {
to: {
subscriberId: req.body.subscriberId,
},
payload: {},
});
res.send(status);
} catch (err) {
console.log(err);
}
});
const PORT = process.env.PORT || 8000;
app.listen(PORT, () => console.log(`Server started at ${PORT}`));
In the try-catch block, we are initiating the bell-notification
template. It is being initiated by novu.trigger
. In to
, we are sending the subscriberId of the receiver. You can pass more data such as name in the payload.
We are sending back the status of the call such as 401 and 200 to our frontend. On this status basis, we are going the decide whether the notification is successfully sent or not.
Testing the Applicaiton
Run the server with the below command:
node server.js
It should print "Server started at 8000" in the console.
Run the React with the below command:
npm run start
It will run the React at http://localhost:3000/
. It should look like this:
Now, if you click on the Send Notificaiton
button a notification will be sent. As our fronted will receive the notification. The bell icon will change to show the notification. Click on the bell icon to access the notification.
Conclusion
We have built the notification bell using the Novu. You can add a button to this notification to redirect the user once they click on it. You might encounter a few warnings in the console while running React. It is caused by the '@novu/notification-center` library. I tried to solve it but couldn't find any solution. If you find something, do mention it in the comment.
Novu can provide you with many interesting features of notification. You can read the Notification Center for React Component from their docs for adding more features to the existing project.
I hope this guide has provided you with useful information about Novu and its In-App notification. Thanks for reading the blog post.
Explore other topics
javascript
Axios to consume REST API in React
Introduction Today, most applications build consume data from an API. These API centric applications have various ways and technologies used to make requests to the API. How do you consume API in you...
March 23, 2023
javascript
Building a Video Player in React
Introduction React has been the most popular JavaScript framework for building frontend. As a web developer, I recommend you learn React. For learning, nothing is better than building a project with ...
March 23, 2023
javascript
What is Asynchronous JavaScript?
One word every JavaScript developer finds it common in most tutorials or documentation is 'asynchronous'. The asynchronous concept of JavaScript becomes a bit confusing if you are a beginner. In this ...
March 23, 2023