Building a live-event alert system with React, Socket.io, and Push Notifications 🚀
You want everybody to get a message on your website once something happens in real-time. That can be a new version, announcement, or some product updates.
What is this article about?
In this article, I’ll guide you on building an event scheduling system with React and Socket.io. The application will allow the users to set reminders for upcoming events, then show a toaster when it’s time for an event.
Toaster = a small box on the screen with the notification.
There are multiple way to get live information from your server about a new event:
- Use long-polling HTTP request, basically an HTTP request every 10 – 30 seconds to get information about a new event.
- Use an open-socket (Websockets) to get information directly from the server when a new bid arrives.
In this article I will talk about Websockets and specifically on the Node.js library – Socket.io
Socket.io is a popular JavaScript library that allows us to create real-time, bi-directional communication between web browsers and a Node.js server. It is a highly performant and reliable library optimized to process a large volume of data with minimal delay. It follows the WebSocket protocol and provides better functionalities, such as fallback to HTTP long-polling or automatic reconnection, which enables us to build efficient real-time applications.
Novu – the first open-source notification infrastructure
Just a quick background about us. Novu is the first open-source notification infrastructure. We basically help to manage all the product notifications. It can be In-App (the bell icon like you have in the Dev Community – Websockets), Emails, SMSs, and so on.
I would be super happy if you could give us a star! It will help me to make more articles every week 🚀
https://github.com/novuhq/novu
Connecting Socket.Io with React 😎
Here, we’ll set up the project environment for the event scheduling system. You’ll also learn how to add Socket.io to a React and Node.js application and connect both development servers for real-time communication via Socket.io.
Create the project folder containing two sub-folders named client and server.
1mkdir event-scheduler
2cd event-scheduler
3mkdir client server
Navigate into the client folder via your terminal and create a new React.js project.
1cd client
2npx create-react-app ./
Install Socket.io client API and React Router. React Router is a JavaScript library that enables us to navigate between pages in a React application.
1npm install socket.io-client react-router-dom
Delete the redundant files such as the logo and the test files from the React app, and update the App.js
file to display Hello World as below.
1function App() {
2 return (
3 <div>
4 <p>Hello World!</p>
5 </div>
6 );
7}
8export default App;
Navigate into the server folder and create a package.json
file.
1cd server & npm init -y
Install Express.js, CORS, Nodemon, and Socket.io Server API.
Express.js is a fast, minimalist framework that provides several features for building web applications in Node.js. CORS is a Node.js package that allows communication between different domains.
Nodemon is a Node.js tool that automatically restarts the server after detecting file changes, and Socket.io allows us to configure a real-time connection on the server.
1npm install express cors nodemon socket.io
Create an index.js
file – the entry point to the web server.
1touch index.js
Set up a simple Node.js server using Express.js. The code snippet below returns a JSON object when you visit the http://localhost:4000/api
in your browser.
1//index.js
2const express = require("express");
3const app = express();
4const PORT = 4000;
5
6app.use(express.urlencoded({ extended: true }));
7app.use(express.json());
8
9app.get("/api", (req, res) => {
10 res.json({
11 message: "Hello world",
12 });
13});
14
15app.listen(PORT, () => {
16 console.log(`Server listening on ${PORT}`);
17});
Import the HTTP and the CORS library to allow data transfer between the client and the server domains.
1const express = require("express");
2const app = express();
3const PORT = 4000;
4
5app.use(express.urlencoded({ extended: true }));
6app.use(express.json());
7
8//New imports
9const http = require("http").Server(app);
10const cors = require("cors");
11
12app.use(cors());
13
14app.get("/api", (req, res) => {
15 res.json({
16 message: "Hello world",
17 });
18});
19
20http.listen(PORT, () => {
21 console.log(`Server listening on ${PORT}`);
22});
Next, add Socket.io to the project to create a real-time connection. Before the app.get()
block, copy the code below. Next, add Socket.io to the project to create a real-time connection. Before the app.get()
block, copy the code below.
1//New imports
2.....
3const socketIO = require('socket.io')(http, {
4 cors: {
5 origin: "http://localhost:3000"
6 }
7});
8
9//Add this before the app.get() block
10socketIO.on('connection', (socket) => {
11 console.log(`⚡: ${socket.id} user just connected!`);
12 socket.on('disconnect', () => {
13 console.log('🔥: A user disconnected');
14 });
15});
From the code snippet above, the socket.io("connection")
function establishes a connection with the React app, then creates a unique ID for each socket and logs the ID to the console whenever a user visits the web page.
When you refresh or close the web page, the socket fires the disconnect event showing that a user has disconnected from the socket.
Configure Nodemon by adding the start command to the list of scripts in the package.json
file. The code snippet below starts the server using Nodemon.
1//In server/package.json
2
3"scripts": {
4 "test": "echo \"Error: no test specified\" && exit 1",
5 "start": "nodemon index.js"
6 },
You can now run the server with Nodemon by using the command below.
1npm start
Open the App.js
file in the client folder and connect the React app to the Socket.io server.
1import socketIO from "socket.io-client";
2const socket = socketIO.connect("http://localhost:4000");
3
4function App() {
5 return (
6 <div>
7 <p>Hello World!</p>
8 </div>
9 );
10}
11export default App;
Start the React.js server.
1npm start
Check the terminal where the server is running; the ID of the React.js client should appear on the terminal.
Congratulations 🥂 , the React app has been successfully connected to the server via Socket.io.
Application Interface 📲
In this section, I’ll guide you through building the user interface for the event scheduling system. It’s a single-page application containing three components: a digital clock, form fields for creating event schedules, and a section that lists upcoming events.
Update the App.js
file as below:
1import React from "react";
2import Clock from "./components/Clock";
3import CreateSchedule from "./components/CreateSchedule";
4import Schedules from "./components/Schedules";
5import socketIO from "socket.io-client";
6
7const socket = socketIO.connect("http://localhost:4000");
8
9const App = () => {
10 return (
11 <div className='app__container'>
12 <Clock />
13 <CreateSchedule />
14 <Schedules />
15 </div>
16 );
17};
18
19export default App;
Navigate into the src/index.css
file and copy the code below. It contains all the CSS required for styling this project.
1@import url("https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&display=swap");
2* {
3 box-sizing: border-box;
4 font-family: "Space Grotesk", sans-serif;
5}
6body {
7 margin: 0;
8 padding: 0;
9}
10.app__container {
11 display: flex;
12 flex-direction: column;
13 width: 100%;
14 min-height: 100vh;
15 padding: 30px;
16}
17.clock__container {
18 width: 100%;
19 display: flex;
20 align-items: center;
21 justify-content: center;
22 height: 20vh;
23 background-color: #f0ebe3;
24 margin-bottom: 30px;
25}
26.clock {
27 font-size: 50px;
28 color: #576f72;
29}
30.createSchedule__container {
31 margin-bottom: 30px;
32 width: 70%;
33}
34form div {
35 margin-bottom: 20px;
36}
37input {
38 margin-left: 20px;
39 padding: 5px;
40 width: 100px;
41}
42#title {
43 width: 70%;
44}
45button {
46 width: 200px;
47 padding: 15px;
48 font-size: 16px;
49 border: none;
50 outline: none;
51 background-color: #576f72;
52 color: #fff;
53 cursor: pointer;
54}
Clock component ⏰
Copy the code into the Clock.js
file to display the current time.
1import React, { useState, useEffect } from "react";
2
3const Clock = () => {
4 const [date, setDate] = useState(new Date());
5
6 const refreshClock = () => setDate(new Date());
7
8 useEffect(() => {
9 const timerId = setInterval(refreshClock, 1000);
10 return () => clearInterval(timerId);
11 }, []);
12
13 return (
14 <div className='clock__container'>
15 <h2 className='clock'>{date.toLocaleTimeString()}</h2>
16 </div>
17 );
18};
19
20export default Clock;
Building the Schedule component 📅
Copy the code below into the CreateSchedule.js
file. It displays a form that allows users to set a time and title for an event.
1import React, { useState } from "react";
2
3const CreateSchedule = () => {
4 const [hour, setHour] = useState(0);
5 const [minute, setMinute] = useState(0);
6 const [title, setTitle] = useState("");
7
8 const handleSubmit = (e) => {
9 e.preventDefault();
10 console.log({ hour, minute, title });
11 setHour("");
12 setMinute("");
13 setTitle("");
14 };
15 return (
16 <div className='createSchedule__container'>
17 <h2>Create a Schedule</h2>
18 <form onSubmit={handleSubmit}>
19 <div className='title__container'>
20 <label htmlFor='title'>Title</label>
21 <input
22 type='text'
23 name='title'
24 id='title'
25 value={title}
26 required
27 onChange={(e) => setTitle(e.target.value)}
28 />
29 </div>
30
31 <div>
32 <label htmlFor='hour'>Select Hour</label>
33 <input
34 type='number'
35 min={0}
36 max={23}
37 name='hour'
38 id='hour'
39 value={hour}
40 onChange={(e) => setHour(e.target.value)}
41 required
42 />
43 </div>
44 <div>
45 <label htmlFor='minute'>Select Minute</label>
46 <input
47 type='number'
48 min={0}
49 max={59}
50 name='minute'
51 id='minute'
52 value={minute}
53 onChange={(e) => setMinute(e.target.value)}
54 required
55 />
56 </div>
57 <button>Submit</button>
58 </form>
59 </div>
60 );
61};
62
63export default CreateSchedule;
Multiple Schedule Components 🗓 📅
The code snippet below displays the upcoming events.
1import React from "react";
2
3const Schedules = () => {
4
5 //create dummy schedules for now
6 const schedules = [
7 {title: "Build React project", hour: 12, minute: 0},
8 {title: "Dance class", hour: 14, minute: 30}]
9 return (
10 <div>
11 <h2>Upcoming Events</h2>
12 <ul>
13 {schedules?.map((schedule) => (
14 <li key={schedule.title}>
15 {schedule.title} - {schedule.hour} : {schedule.minute}
16 </li>
17 ))}
18 </ul>
19 </div>
20 );
21};
22
23export default Schedules;
Connecting the application to the Socket.io server
In this section, you’ll learn how to save the event schedules to the Node.js server and send notifications to the React app whenever it’s time for a particular event.
Saving the events to the backend server 💾
Here, I’ll guide you through sending and saving the schedules to the backend Node.js server.
Pass Socket.io into the CreateSchedule
component in the App.js
file.
1import React from "react";
2import Clock from "./components/Clock";
3import CreateSchedule from "./components/CreateSchedule";
4import Schedules from "./components/Schedules";
5import socketIO from "socket.io-client";
6
7const socket = socketIO.connect("http://localhost:4000");
8
9const App = () => {
10 return (
11 <div className='app__container'>
12 <Clock />
13 <CreateSchedule socket={socket} />
14 <Schedules />
15 </div>
16 );
17};
18
19export default App;
Update the handleSubmit
function to send the event details to the Node.js server via Socket.io.
1import React, { useState } from "react";
2
3const CreateSchedule = ({ socket }) => {
4 const [hour, setHour] = useState(0);
5 const [minute, setMinute] = useState(0);
6 const [title, setTitle] = useState("");
7
8 const handleSubmit = (e) => {
9 e.preventDefault();
10 //sends the event details via Socket.io
11 socket.emit("newEvent", { hour, minute, title });
12 setHour("");
13 setMinute("");
14 setTitle("");
15 };
16 return <div className='createSchedule__container'>...</div>;
17};
18
19export default CreateSchedule;
Create the event listener on the Node.js server that accepts the data from the React app. The code snippet below logs the event details to the terminal.
1socketIO.on("connection", (socket) => {
2 console.log(`⚡: ${socket.id} user just connected!`);
3
4 //event listener for new events
5 socket.on("newEvent", (event) => {
6 console.log(event);
7 });
8
9 socket.on("disconnect", () => {
10 socket.disconnect();
11 });
12});
Save the events to an array and send the list of events back to the React app.
1let eventList = [];
2
3socketIO.on("connection", (socket) => {
4 console.log(`⚡: ${socket.id} user just connected!`);
5
6 /*
7 The event listener adds the new event
8 to the top of the array, and
9 sends the array to the React app
10 */
11 socket.on("newEvent", (event) => {
12 eventList.unshift(event);
13 //sends the events back to the React app
14 socket.emit("sendSchedules", eventList);
15 });
16
17 socket.on("disconnect", () => {
18 socket.disconnect();
19 });
20});
Create an event listener for the sendSchedules
message in the App.js
file.
1import React, { useEffect, useState } from "react";
2import Clock from "./components/Clock";
3import CreateSchedule from "./components/CreateSchedule";
4import Schedules from "./components/Schedules";
5import socketIO from "socket.io-client";
6
7const socket = socketIO.connect("http://localhost:4000");
8
9const App = () => {
10 const [schedules, setSchedules] = useState([]);
11
12 useEffect(() => {
13 //listens for the event list from the backend
14 socket.on("sendSchedules", (schedules) => {
15 setSchedules(schedules);
16 });
17 }, []);
18
19 return (
20 <div className='app__container'>
21 <Clock />
22 <CreateSchedule socket={socket} />
23 <Schedules schedules={schedules} />
24 </div>
25 );
26};
27
28export default App;
The code snippet above accepts the event list from the backend and passes the array of events (schedules) into the Schedules
component.
Update the Schedules
component as below:
1import React from "react";
2
3const Schedules = ({ schedules }) => {
4 return (
5 <div>
6 <h2>Upcoming Events</h2>
7 <ul>
8 {schedules?.map((schedule) => (
9 <li key={schedule.title}>
10 {schedule.title} - {schedule.hour} : {schedule.minute}
11 </li>
12 ))}
13 </ul>
14 </div>
15 );
16};
17
18export default Schedules;
Congratulations!💃🏻 We’ve been able to save on the server and display the events on the client. Next, let’s send notifications to the user when it’s time for the event.
Adding notifications with React Toastify
In this section, I’ll guide you through sending notifications to the React app when a user adds an event and when it’s time for an event.
Install and configure React Toastify as below:
1//In App.js file
2import React, { useEffect, useState } from "react";
3import Clock from "./components/Clock";
4import CreateSchedule from "./components/CreateSchedule";
5import Schedules from "./components/Schedules";
6import socketIO from "socket.io-client";
7
8//React Toastify imports
9import "react-toastify/dist/ReactToastify.css";
10import { ToastContainer, toast } from "react-toastify";
11
12const socket = socketIO.connect("http://localhost:4000");
13
14const App = () => {
15 const [schedules, setSchedules] = useState([]);
16
17 useEffect(() => {
18 socket.on("sendSchedules", (schedules) => {
19 setSchedules(schedules);
20 });
21 }, []);
22
23 return (
24 <div className='app__container'>
25 <Clock />
26 <CreateSchedule socket={socket} />
27 <Schedules schedules={schedules} />
28 <ToastContainer />
29 </div>
30 );
31};
32
33export default App;
Update the CreateSchedule
component to show notifications when a user adds an event schedule.
1import React, { useState } from "react";
2import { toast } from "react-toastify";
3
4const CreateSchedule = ({ socket }) => {
5 const [hour, setHour] = useState(0);
6 const [minute, setMinute] = useState(0);
7 const [title, setTitle] = useState("");
8
9 const handleSubmit = (e) => {
10 e.preventDefault();
11 socket.emit("newSchedule", { hour, minute, title });
12 //👇🏻 shows toast notifications
13 toast.success(`${title} is successfully added!`);
14 setHour("");
15 setMinute("");
16 setTitle("");
17 };
18 return <div className='createSchedule__container'>...</div>;
19};
20
21export default CreateSchedule;
Update the server/index.js
1let eventList = [];
2
3socketIO.on("connection", (socket) => {
4 console.log(`⚡: ${socket.id} user just connected!`);
5
6 socket.on("newEvent", (event) => {
7 eventList.unshift(event);
8 socket.emit("sendSchedules", eventList);
9 });
10 /*
11 The code snippet loops through the event list
12 and checks if it's time for any event
13 before sending a message containing
14 the event details to the React app
15 */
16
17 let interval = setInterval(function () {
18 if (eventList.length > 0) {
19 for (let i = 0; i < eventList.length; i++) {
20 if (
21 Number(eventList[i].hour) === new Date().getHours() &&
22 Number(eventList[i].minute) === new Date().getMinutes() &&
23 new Date().getSeconds() === 0
24 ) {
25 socket.emit("notification", {
26 title: eventList[i].title,
27 hour: eventList[i].hour,
28 mins: eventList[i].minute,
29 });
30 }
31 }
32 }
33 }, 1000);
34
35 socket.on("disconnect", () => {
36 socket.disconnect();
37 });
38});
Update the App.js
file to display notifications when it is time for an event.
1import React, { useEffect, useState } from "react";
2import Clock from "./components/Clock";
3import CreateSchedule from "./components/CreateSchedule";
4import Schedules from "./components/Schedules";
5import socketIO from "socket.io-client";
6import "react-toastify/dist/ReactToastify.css";
7import { ToastContainer } from "react-toastify";
8import { toast } from "react-toastify";
9
10const socket = socketIO.connect("http://localhost:4000");
11
12const App = () => {
13 const [schedules, setSchedules] = useState([]);
14
15 useEffect(() => {
16 socket.on("sendSchedules", (schedules) => {
17 setSchedules(schedules);
18 });
19 //Listens for the notification from the server
20 socket.on("notification", (data) => {
21 toast.success(` It's time for ${data.title}`);
22 });
23 }, []);
24
25 return (
26 <div className='app__container'>
27 <Clock />
28 <CreateSchedule socket={socket} />
29 <Schedules schedules={schedules} />
30 <ToastContainer />
31 </div>
32 );
33};
34
35export default App;
You have finished the basic event scheduling and showing it on the browser 💁🏻♀️
EXTRA: Sending push notifications to the user 🙋🏻♂️
What if the web page is not open? How do we ensure that users don’t miss their schedules and get notified even when they are not on the web page?
Push notification is the best solution.
A push notification appears on your desktop or home screen even when the web application is not open. Here, I will guide you through sending push notifications with Firebase and Novu.
Setting up Firebase Cloud Messaging
Go to the Firebase Console, sign in, and create a Firebase project.
Create a Firebase Web app within the project by clicking the </>
icon.
Create a src/firebase.js
file and copy the Firebase JavaScript SDK configuration into the file
1//👉🏻 In client/src/firebase.js
2import { initializeApp } from "firebase/app";
3
4const firebaseConfig = {
5 apiKey: "...",
6 authDomain: "...",
7 projectId: "...",
8 storageBucket: "...",
9 messagingSenderId: "...",
10 appId: "...",
11};
12
13// Initialize Firebase
14const app = initializeApp(firebaseConfig);
Install Firebase to your React project.
1cd client
2npm install firebase
Click on the Settings icon beside Project Overview on the sidebar of the Firebase app dashboard, and select Project settings.
Navigate to the Cloud Messaging tab and generate a Web Push certificate key pair.
Update the firebase.js
file to contain the code below and add the Web Push certificate as the vapidKey
variable.
1import { initializeApp } from "firebase/app";
2import { getMessaging, getToken, onMessage } from "firebase/messaging";
3
4const firebaseConfig = {
5 apiKey: "...",
6 authDomain: "...",
7 projectId: "...",
8 storageBucket: "...",
9 messagingSenderId: "...",
10 appId: "...",
11 measurementId: "...",
12};
13
14// Initialize Firebase
15const firebaseApp = initializeApp(firebaseConfig);
16//Access Firebase cloud messaging
17const messaging = getMessaging(firebaseApp);
18
19/*
20This function allows us to get your device token from Firebase
21which is required for sending Push notifications to your device.
22*/
23export const getTokenFromFirebase = () => {
24 return getToken(messaging, {
25 vapidKey: "<YOUR_WEB_PUSH_CERTIFICATE>",
26 })
27 .then((currentToken) => {
28 if (currentToken) {
29 console.log("current token for client: ", currentToken);
30 } else {
31 console.log(
32 "No registration token available. Request permission to generate one."
33 );
34 }
35 })
36 .catch((err) => {
37 console.log("An error occurred while retrieving token. ", err);
38 });
39};
40
41//This function listens to push messages on the server
42export const onMessageListener = () =>
43 new Promise((resolve) => {
44 onMessage(messaging, (payload) => {
45 console.log(payload);
46 resolve(payload);
47 });
48 });
Create a service worker file within the public folder of your React app.
1cd client/public
2touch firebase-messaging-sw.js
Copy the code snippet below into the firebase-messaging-sw.js
file.
1// Scripts for firebase and firebase messaging
2importScripts(
3 "https://www.gstatic.com/firebasejs/9.0.0/firebase-app-compat.js"
4);
5importScripts(
6 "https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-compat.js"
7);
8
9const firebaseConfig = {
10 apiKey: "...",
11 authDomain: "...",
12 projectId: "...",
13 storageBucket: "...",
14 messagingSenderId: "...",
15 appId: "...",
16 measurementId: "...",
17};
18
19firebase.initializeApp(firebaseConfig);
20
21// Retrieve firebase messaging
22const messaging = firebase.messaging();
23
24messaging.onBackgroundMessage(function (payload) {
25 console.log("Received background message ", payload);
26 const notificationTitle = payload.notification.title;
27 const notificationOptions = {
28 body: payload.notification.body,
29 };
30
31 self.registration.showNotification(notificationTitle, notificationOptions);
32});
Navigate into the App.js
file and call the functions from the firebase.js
file.
1//....other imports
2
3//👉🏻 Import the functions from the Firebase.js file
4import { getTokenFromFirebase, onMessageListener } from "./firebase";
5
6const socket = socketIO.connect("http://localhost:4000");
7
8const App = () => {
9 const [schedules, setSchedules] = useState([]);
10
11 useEffect(() => {
12 //👉🏻Logs the device token to the console
13 getTokenFromFirebase();
14
15 //👉🏻Listen and logs the push messages from the server.
16 onMessageListener()
17 .then((payload) => {
18 console.log("From Message", payload);
19 })
20 .catch((err) => console.log("failed: ", err));
21
22 //....socket.io listeners
23 }, []);
24
25 return (
26 ...
27 );
28};
29
30export default App;
Run the React app server; your device token will appear in the console. Copy the token and save it for use in the upcoming section.
Exporting Firebase 🔥
Go back to your Firebase app dashboard. Under Project settings, navigate to the Service Accounts tab, and download your Service account credentials (JSON file type) by clicking the Generate a new private key
button.
Novu – open-source library
We can use Novu to send push notifications to the user once there is a new notification, you can also use other services such as OneSignal, or you can implement it yourself.
Navigate into the client folder and create a Novu project by running the code below.
1cd client
2npx novu init
You will need to sign in with GitHub before creating a Novu project. The code snippet below contains the steps you should follow after running npx novu init
1Now let's setup your account and send your first notification
2❓ What is your application name? Devto Clone
3❓ Now lets setup your environment. How would you like to proceed?
4 > Create a free cloud account (Recommended)
5❓ Create your account with:
6 > Sign-in with GitHub
7❓ I accept the Terms and Condidtions (https://novu.co/terms) and have read the Privacy Policy (https://novu.co/privacy)
8 > Yes
9✔️ Create your account successfully.
10
11We've created a demo web page for you to see novu notifications in action.
12Visit: http://localhost:57807/demo to continue
Visit the demo web page http://localhost:57807/demo
, copy your subscriber ID from the page, and click the Skip Tutorial button. We’ll be using it later in this tutorial.
Select Push under the Integration Store section on your dashboard, copy the contents of the already downloaded Service Account credentials into the input field and save.
Select Notifications from the sidebar, and create a notification template for the push messages.
Edit the template by adding Push to its workflow
Select the Push step, add the push notification content, and save.
Next, install and configure Novu on the server.
1/*
2👉🏻 Run npm install @novu/node in your terminal
3*/
4const { Novu, PushProviderIdEnum } = require("@novu/node");
5const novu = new Novu("<YOUR_API_KEY>");
Send the push notifications request via Novu in the server/index.js
file by updating the /api
route as below:
1app.get("/api", async (req, res) => {
2 const subscriberId = "<YOUR_NOVU_SUBSCRIBER_ID>";
3 await novu.subscribers.identify(subscriberId, {
4 firstName: "<YOUR_FIRST_NAME>",
5 lastName: "<YOUR_LAST_NAME>",
6 });
7
8 await novu.subscribers.setCredentials(subscriberId, PushProviderIdEnum.FCM, {
9 deviceTokens: ["<YOUR_DEVICE_TOKEN_FROM_REACT_APP_CONSOLE>"],
10 });
11
12 const trigger = await novu.trigger("<NOTIFICATION_TEMPLATE_ID>", {
13 to: {
14 subscriberId,
15 },
16 });
17
18 res.json(trigger.data);
19});
Congratulations! We’ve been able to send push notifications via Novu.
NB: When you check your React app JavaScript console, it also logs the push notification content.
To send the notification when it’s time for an event, create a function that sends the push notification via Novu when it’s time for an event as below:
1async function sendNotification(message) {
2 const subscriberId = "<YOUR_NOVU_SUBSCRIBER_ID>";
3 await novu.subscribers.identify(subscriberId, {
4 firstName: "<YOUR_FIRST_NAME>",
5 lastName: "<YOUR_LAST_NAME>",
6 });
7
8 await novu.subscribers.setCredentials(subscriberId, PushProviderIdEnum.FCM, {
9 deviceTokens: ["<YOUR_DEVICE_TOKEN_FROM_REACT_APP_CONSOLE>"],
10 });
11
12 const trigger = await novu.trigger("<NOTIFICATION_TEMPLATE_ID>", {
13 to: {
14 subscriberId,
15 },
16 /*👇🏻 payload allows you to pass data into the notification template
17 Read more here: https://docs.novu.co/platform/templates/#variable-usage
18 */
19 payload: {
20 message,
21 },
22 });
23}
24
25socketIO.on("connection", (socket) => {
26 console.log(`⚡: ${socket.id} user just connected!`);
27
28 socket.on("newSchedule", (schedule) => {
29 eventList.unshift(schedule);
30 socket.emit("sendSchedules", eventList);
31 });
32
33 let interval = setInterval(function () {
34 if (eventList.length > 0) {
35 for (let i = 0; i < eventList.length; i++) {
36 if (
37 Number(eventList[i].hour) === new Date().getHours() &&
38 Number(eventList[i].minute) === new Date().getMinutes() &&
39 new Date().getSeconds() === 0
40 ) {
41 sendNotification(eventList[i].title);
42 }
43 }
44 }
45 }, 1000);
46
47 socket.on("disconnect", () => {
48 socket.disconnect();
49 });
50});
Conclusion
So far, you’ve learned how to add a digital clock to a React app, send messages and notifications at intervals between a React app and Socket.io server, and send push notifications to users with Novu and Firebase.
You can also improve this application and add push notifications to various applications with Novu and Firebase.
The source code for this tutorial is available here: https://github.com/novuhq/blog/tree/main/event-scheduler-with-push-notifications
Thank you for reading!