DEV Community

Cover image for Building a live-event alert system with React, Socket.io, and Push Notifications ๐Ÿš€
Nevo David for novu

Posted on • Originally published at novu.co

Building a live-event alert system with React, Socket.io, and Push Notifications ๐Ÿš€

What is this article about?

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.

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.

Toast

There multiple way to get live information from your server about a new event:

  1. Use long-polling HTTP request, basically an HTTP request every 10 - 30 seconds to get information about a new event.

  2. 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

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.

mkdir event-scheduler
cd event-scheduler
mkdir client server
Enter fullscreen mode Exit fullscreen mode

Navigate into the client folder via your terminal and create a new React.js project.

cd client
npx create-react-app ./
Enter fullscreen mode Exit fullscreen mode

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.

npm install socket.io-client react-router-dom
Enter fullscreen mode Exit fullscreen mode

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.

function App() {
    return (
        <div>
            <p>Hello World!</p>
        </div>
    );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

Navigate into the server folder and create a package.json file.

cd server & npm init -y
Enter fullscreen mode Exit fullscreen mode

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.

npm install express cors nodemon socket.io
Enter fullscreen mode Exit fullscreen mode

Create an index.js file - the entry point to the web server.

touch index.js
Enter fullscreen mode Exit fullscreen mode

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.

//index.js
const express = require("express");
const app = express();
const PORT = 4000;

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.get("/api", (req, res) => {
    res.json({
        message: "Hello world",
    });
});

app.listen(PORT, () => {
    console.log(`Server listening on ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Import the HTTP and the CORS library to allow data transfer between the client and the server domains.

const express = require("express");
const app = express();
const PORT = 4000;

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

//New imports
const http = require("http").Server(app);
const cors = require("cors");

app.use(cors());

app.get("/api", (req, res) => {
    res.json({
        message: "Hello world",
    });
});

http.listen(PORT, () => {
    console.log(`Server listening on ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

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.

//New imports
.....
const socketIO = require('socket.io')(http, {
    cors: {
        origin: "http://localhost:3000"
    }
});

//Add this before the app.get() block
socketIO.on('connection', (socket) => {
    console.log(`โšก: ${socket.id} user just connected!`);
    socket.on('disconnect', () => {
      console.log('๐Ÿ”ฅ: A user disconnected');
    });
});
Enter fullscreen mode Exit fullscreen mode

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.

//In server/package.json

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon index.js"
  },
Enter fullscreen mode Exit fullscreen mode

You can now run the server with Nodemon by using the command below.

npm start
Enter fullscreen mode Exit fullscreen mode

Open the App.js file in the client folder and connect the React app to the Socket.io server.

import socketIO from "socket.io-client";
const socket = socketIO.connect("http://localhost:4000");

function App() {
    return (
        <div>
            <p>Hello World!</p>
        </div>
    );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

Start the React.js server.

npm start
Enter fullscreen mode Exit fullscreen mode

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.

Schedule

Update the App.js file as below:

import React from "react";
import Clock from "./components/Clock";
import CreateSchedule from "./components/CreateSchedule";
import Schedules from "./components/Schedules";
import socketIO from "socket.io-client";

const socket = socketIO.connect("http://localhost:4000");

const App = () => {
    return (
        <div className='app__container'>
            <Clock />
            <CreateSchedule />
            <Schedules />
        </div>
    );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Navigate into the src/index.css file and copy the code below. It contains all the CSS required for styling this project.

@import url("https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&display=swap");
* {
    box-sizing: border-box;
    font-family: "Space Grotesk", sans-serif;
}
body {
    margin: 0;
    padding: 0;
}
.app__container {
    display: flex;
    flex-direction: column;
    width: 100%;
    min-height: 100vh;
    padding: 30px;
}
.clock__container {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 20vh;
    background-color: #f0ebe3;
    margin-bottom: 30px;
}
.clock {
    font-size: 50px;
    color: #576f72;
}
.createSchedule__container {
    margin-bottom: 30px;
    width: 70%;
}
form div {
    margin-bottom: 20px;
}
input {
    margin-left: 20px;
    padding: 5px;
    width: 100px;
}
#title {
    width: 70%;
}
button {
    width: 200px;
    padding: 15px;
    font-size: 16px;
    border: none;
    outline: none;
    background-color: #576f72;
    color: #fff;
    cursor: pointer;
}
Enter fullscreen mode Exit fullscreen mode

Clock component โฐ

Copy the code into the Clock.js file to display the current time.

import React, { useState, useEffect } from "react";

const Clock = () => {
    const [date, setDate] = useState(new Date());

    const refreshClock = () => setDate(new Date());

    useEffect(() => {
        const timerId = setInterval(refreshClock, 1000);
        return () => clearInterval(timerId);
    }, []);

    return (
        <div className='clock__container'>
            <h2 className='clock'>{date.toLocaleTimeString()}</h2>
        </div>
    );
};

export default Clock;
Enter fullscreen mode Exit fullscreen mode

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.

import React, { useState } from "react";

const CreateSchedule = () => {
    const [hour, setHour] = useState(0);
    const [minute, setMinute] = useState(0);
    const [title, setTitle] = useState("");

    const handleSubmit = (e) => {
        e.preventDefault();
        console.log({ hour, minute, title });
        setHour("");
        setMinute("");
        setTitle("");
    };
    return (
        <div className='createSchedule__container'>
            <h2>Create a Schedule</h2>
            <form onSubmit={handleSubmit}>
                <div className='title__container'>
                    <label htmlFor='title'>Title</label>
                    <input
                        type='text'
                        name='title'
                        id='title'
                        value={title}
                        required
                        onChange={(e) => setTitle(e.target.value)}
                    />
                </div>

                <div>
                    <label htmlFor='hour'>Select Hour</label>
                    <input
                        type='number'
                        min={0}
                        max={23}
                        name='hour'
                        id='hour'
                        value={hour}
                        onChange={(e) => setHour(e.target.value)}
                        required
                    />
                </div>
                <div>
                    <label htmlFor='minute'>Select Minute</label>
                    <input
                        type='number'
                        min={0}
                        max={59}
                        name='minute'
                        id='minute'
                        value={minute}
                        onChange={(e) => setMinute(e.target.value)}
                        required
                    />
                </div>
                <button>Submit</button>
            </form>
        </div>
    );
};

export default CreateSchedule;
Enter fullscreen mode Exit fullscreen mode

Multiple Schedule Components ๐Ÿ—“ ๐Ÿ“…

The code snippet below displays the upcoming events.

import React from "react";

const Schedules = () => {

    //create dummy schedules for now
    const schedules = [
        {title: "Build React project", hour: 12, minute: 0},
        {title: "Dance class", hour: 14, minute: 30}]
    return (
        <div>
            <h2>Upcoming Events</h2>
            <ul>
                {schedules?.map((schedule) => (
                    <li key={schedule.title}>
                        {schedule.title} - {schedule.hour} : {schedule.minute}
                    </li>
                ))}
            </ul>
        </div>
    );
};

export default Schedules;
Enter fullscreen mode Exit fullscreen mode

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.

import React from "react";
import Clock from "./components/Clock";
import CreateSchedule from "./components/CreateSchedule";
import Schedules from "./components/Schedules";
import socketIO from "socket.io-client";

const socket = socketIO.connect("http://localhost:4000");

const App = () => {
    return (
        <div className='app__container'>
            <Clock />
            <CreateSchedule socket={socket} />
            <Schedules />
        </div>
    );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Update the handleSubmit function to send the event details to the Node.js server via Socket.io.

import React, { useState } from "react";

const CreateSchedule = ({ socket }) => {
    const [hour, setHour] = useState(0);
    const [minute, setMinute] = useState(0);
    const [title, setTitle] = useState("");

    const handleSubmit = (e) => {
        e.preventDefault();
        //sends the event details via Socket.io
        socket.emit("newEvent", { hour, minute, title });
        setHour("");
        setMinute("");
        setTitle("");
    };
    return <div className='createSchedule__container'>...</div>;
};

export default CreateSchedule;

Enter fullscreen mode Exit fullscreen mode

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.

socketIO.on("connection", (socket) => {
    console.log(`โšก: ${socket.id} user just connected!`);

    //event listener for new events
    socket.on("newEvent", (event) => {
        console.log(event);
    });

    socket.on("disconnect", () => {
        socket.disconnect();
    });
});
Enter fullscreen mode Exit fullscreen mode

Save the events to an array and send the list of events back to the React app.

let eventList = [];

socketIO.on("connection", (socket) => {
    console.log(`โšก: ${socket.id} user just connected!`);

    /*
    The event listener adds the new event 
        to the top of the array, and 
        sends the array to the React app
    */
    socket.on("newEvent", (event) => {
        eventList.unshift(event);
        //sends the events back to the React app
        socket.emit("sendSchedules", eventList);
    });

    socket.on("disconnect", () => {
        socket.disconnect();
    });
});
Enter fullscreen mode Exit fullscreen mode

Create an event listener for the sendSchedules message in the App.js file.

import React, { useEffect, useState } from "react";
import Clock from "./components/Clock";
import CreateSchedule from "./components/CreateSchedule";
import Schedules from "./components/Schedules";
import socketIO from "socket.io-client";

const socket = socketIO.connect("http://localhost:4000");

const App = () => {
    const [schedules, setSchedules] = useState([]);

    useEffect(() => {
        //listens for the event list from the backend
        socket.on("sendSchedules", (schedules) => {
            setSchedules(schedules);
        });
    }, []);

    return (
        <div className='app__container'>
            <Clock />
            <CreateSchedule socket={socket} />
            <Schedules schedules={schedules} />
        </div>
    );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

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:

import React from "react";

const Schedules = ({ schedules }) => {
    return (
        <div>
            <h2>Upcoming Events</h2>
            <ul>
                {schedules?.map((schedule) => (
                    <li key={schedule.title}>
                        {schedule.title} - {schedule.hour} : {schedule.minute}
                    </li>
                ))}
            </ul>
        </div>
    );
};

export default Schedules;

Enter fullscreen mode Exit fullscreen mode

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:

//In App.js file
import React, { useEffect, useState } from "react";
import Clock from "./components/Clock";
import CreateSchedule from "./components/CreateSchedule";
import Schedules from "./components/Schedules";
import socketIO from "socket.io-client";

//React Toastify imports
import "react-toastify/dist/ReactToastify.css";
import { ToastContainer, toast } from "react-toastify";

const socket = socketIO.connect("http://localhost:4000");

const App = () => {
    const [schedules, setSchedules] = useState([]);

    useEffect(() => {
        socket.on("sendSchedules", (schedules) => {
            setSchedules(schedules);
        });
    }, []);

    return (
        <div className='app__container'>
            <Clock />
            <CreateSchedule socket={socket} />
            <Schedules schedules={schedules} />
            <ToastContainer />
        </div>
    );
};

export default App
Enter fullscreen mode Exit fullscreen mode

Update the CreateSchedule component to show notifications when a user adds an event schedule.

import React, { useState } from "react";
import { toast } from "react-toastify";

const CreateSchedule = ({ socket }) => {
    const [hour, setHour] = useState(0);
    const [minute, setMinute] = useState(0);
    const [title, setTitle] = useState("");

    const handleSubmit = (e) => {
        e.preventDefault();
        socket.emit("newSchedule", { hour, minute, title });
        //๐Ÿ‘‡๐Ÿป shows toast notifications
        toast.success(`${title} is successfully added!`);
        setHour("");
        setMinute("");
        setTitle("");
    };
    return <div className='createSchedule__container'>...</div>;
};

export default CreateSchedule;
Enter fullscreen mode Exit fullscreen mode

Update the server/index.js

let eventList = [];

socketIO.on("connection", (socket) => {
    console.log(`โšก: ${socket.id} user just connected!`);

    socket.on("newEvent", (event) => {
        eventList.unshift(event);
        socket.emit("sendSchedules", eventList);
    });
    /*
    The code snippet loops through the event list 
    and checks if it's time for any event 
    before sending a message containing 
    the event details to the React app
    */

    let interval = setInterval(function () {
        if (eventList.length > 0) {
            for (let i = 0; i < eventList.length; i++) {
                if (
                    Number(eventList[i].hour) === new Date().getHours() &&
                    Number(eventList[i].minute) === new Date().getMinutes() &&
                    new Date().getSeconds() === 0
                ) {
                    socket.emit("notification", {
                        title: eventList[i].title,
                        hour: eventList[i].hour,
                        mins: eventList[i].minute,
                    });
                }
            }
        }
    }, 1000);

    socket.on("disconnect", () => {
        socket.disconnect();
    });
});
Enter fullscreen mode Exit fullscreen mode

Update the App.js file to display notifications when it is time for an event.

import React, { useEffect, useState } from "react";
import Clock from "./components/Clock";
import CreateSchedule from "./components/CreateSchedule";
import Schedules from "./components/Schedules";
import socketIO from "socket.io-client";
import "react-toastify/dist/ReactToastify.css";
import { ToastContainer } from "react-toastify";
import { toast } from "react-toastify";

const socket = socketIO.connect("http://localhost:4000");

const App = () => {
    const [schedules, setSchedules] = useState([]);

    useEffect(() => {
        socket.on("sendSchedules", (schedules) => {
            setSchedules(schedules);
        });
        //Listens for the notification from the server
        socket.on("notification", (data) => {
            toast.success(` It's time for ${data.title}`);
        });
    }, []);

    return (
        <div className='app__container'>
            <Clock />
            <CreateSchedule socket={socket} />
            <Schedules schedules={schedules} />
            <ToastContainer />
        </div>
    );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

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.

Push Notifications

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

//๐Ÿ‘‰๐Ÿป In client/src/firebase.js
import { initializeApp } from "firebase/app";

const firebaseConfig = {
    apiKey: "...",
    authDomain: "...",
    projectId: "...",
    storageBucket: "...",
    messagingSenderId: "...",
    appId: "...",
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
Enter fullscreen mode Exit fullscreen mode

Install Firebase to your React project.

cd client
npm install firebase
Enter fullscreen mode Exit fullscreen mode

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.

Firebase

Update the firebase.js file to contain the code below and add the Web Push certificate as the vapidKey variable.

import { initializeApp } from "firebase/app";
import { getMessaging, getToken, onMessage } from "firebase/messaging";

const firebaseConfig = {
    apiKey: "...",
    authDomain: "...",
    projectId: "...",
    storageBucket: "...",
    messagingSenderId: "...",
    appId: "...",
    measurementId: "...",
};

// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
//Access Firebase cloud messaging
const messaging = getMessaging(firebaseApp);

/*
This function allows us to get your device token from Firebase 
which is required for sending Push notifications to your device.
*/
export const getTokenFromFirebase = () => {
    return getToken(messaging, {
        vapidKey: "<YOUR_WEB_PUSH_CERTIFICATE>",
    })
        .then((currentToken) => {
            if (currentToken) {
                console.log("current token for client: ", currentToken);
            } else {
                console.log(
                    "No registration token available. Request permission to generate one."
                );
            }
        })
        .catch((err) => {
            console.log("An error occurred while retrieving token. ", err);
        });
};

//This function listens to push messages on the server
export const onMessageListener = () =>
    new Promise((resolve) => {
        onMessage(messaging, (payload) => {
            console.log(payload);
            resolve(payload);
        });
    });
Enter fullscreen mode Exit fullscreen mode

Create a service worker file within the public folder of your React app.

cd client/public
touch firebase-messaging-sw.js
Enter fullscreen mode Exit fullscreen mode

Copy the code snippet below into the firebase-messaging-sw.js file.

// Scripts for firebase and firebase messaging
importScripts(
    "https://www.gstatic.com/firebasejs/9.0.0/firebase-app-compat.js"
);
importScripts(
    "https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-compat.js"
);

const firebaseConfig = {
    apiKey: "...",
    authDomain: "...",
    projectId: "...",
    storageBucket: "...",
    messagingSenderId: "...",
    appId: "...",
    measurementId: "...",
};

firebase.initializeApp(firebaseConfig);

// Retrieve firebase messaging
const messaging = firebase.messaging();

messaging.onBackgroundMessage(function (payload) {
    console.log("Received background message ", payload);
    const notificationTitle = payload.notification.title;
    const notificationOptions = {
        body: payload.notification.body,
    };

    self.registration.showNotification(notificationTitle, notificationOptions);
});
Enter fullscreen mode Exit fullscreen mode

Navigate into the App.js file and call the functions from the firebase.js file.

//....other imports

//๐Ÿ‘‰๐Ÿป Import the functions from the Firebase.js file
import { getTokenFromFirebase, onMessageListener } from "./firebase";

const socket = socketIO.connect("http://localhost:4000");

const App = () => {
    const [schedules, setSchedules] = useState([]);

    useEffect(() => {
        //๐Ÿ‘‰๐ŸปLogs the device token to the console
        getTokenFromFirebase();

    //๐Ÿ‘‰๐ŸปListen and logs the push messages from the server.
        onMessageListener()
            .then((payload) => {
                console.log("From Message", payload);
            })
            .catch((err) => console.log("failed: ", err));

       //....socket.io listeners
    }, []);

    return (
        ...
    );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

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.

Firebase

Novu - open-source library

We can use Novu to send push notifications to the user once there is a new notificaitons, 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.

cd client
npx novu init
Enter fullscreen mode Exit fullscreen mode

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

Now let's setup your account and send your first notification
โ“ What is your application name? Devto Clone
โ“ Now lets setup your environment. How would you like to proceed?
   > Create a free cloud account (Recommended)
โ“ Create your account with:
   > Sign-in with GitHub
โ“ I accept the Terms and Condidtions (https://novu.co/terms) and have read the Privacy Policy (https://novu.co/privacy)
    > Yes
โœ”๏ธ Create your account successfully.

We've created a demo web page for you to see novu notifications in action.
Visit: http://localhost:57807/demo to continue
Enter fullscreen mode Exit fullscreen mode

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.

Demo

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.

FCM

Select Notifications from the sidebar, and create a notification template for the push messages.

Edit the template by adding Push to its workflow

Push

Select the Push step, add the push notification content, and save.

Next, install and configure Novu on the server.

/*
๐Ÿ‘‰๐Ÿป Run npm install @novu/node in your terminal
*/
const { Novu, PushProviderIdEnum } = require("@novu/node");
const novu = new Novu("<YOUR_API_KEY>");

Enter fullscreen mode Exit fullscreen mode

Api Keys

Send the push notifications request via Novu in the server/index.js file by updating the /api route as below:

app.get("/api", async (req, res) => {
    const subscriberId = "<YOUR_NOVU_SUBSCRIBER_ID>";
    await novu.subscribers.identify(subscriberId, {
        firstName: "<YOUR_FIRST_NAME>",
        lastName: "<YOUR_LAST_NAME>",
    });

    await novu.subscribers.setCredentials(subscriberId, PushProviderIdEnum.FCM, {
        deviceTokens: ["<YOUR_DEVICE_TOKEN_FROM_REACT_APP_CONSOLE>"],
    });

    const trigger = await novu.trigger("<NOTIFICATION_TEMPLATE_ID>", {
        to: {
            subscriberId,
        },
    });

    res.json(trigger.data);
});
Enter fullscreen mode Exit fullscreen mode

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.

Design

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:

async function sendNotification(message) {
    const subscriberId = "<YOUR_NOVU_SUBSCRIBER_ID>";
    await novu.subscribers.identify(subscriberId, {
        firstName: "<YOUR_FIRST_NAME>",
        lastName: "<YOUR_LAST_NAME>",
    });

    await novu.subscribers.setCredentials(subscriberId, PushProviderIdEnum.FCM, {
        deviceTokens: ["<YOUR_DEVICE_TOKEN_FROM_REACT_APP_CONSOLE>"],
    });

    const trigger = await novu.trigger("<NOTIFICATION_TEMPLATE_ID>", {
        to: {
            subscriberId,
        },
        /*๐Ÿ‘‡๐Ÿป payload allows you to pass data into the notification template
        Read more here: https://docs.novu.co/platform/templates/#variable-usage
        */
        payload: {
            message,
        },
    });
}

socketIO.on("connection", (socket) => {
    console.log(`โšก: ${socket.id} user just connected!`);

    socket.on("newSchedule", (schedule) => {
        eventList.unshift(schedule);
        socket.emit("sendSchedules", eventList);
    });

    let interval = setInterval(function () {
        if (eventList.length > 0) {
            for (let i = 0; i < eventList.length; i++) {
                if (
                    Number(eventList[i].hour) === new Date().getHours() &&
                    Number(eventList[i].minute) === new Date().getMinutes() &&
                    new Date().getSeconds() === 0
                ) {
                    sendNotification(eventList[i].title);
                }
            }
        }
    }, 1000);

    socket.on("disconnect", () => {
        socket.disconnect();
    });
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

So far, you've learnt 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!

Love You

Top comments (3)

Collapse
 
nevodavid profile image
Nevo David

Real Time

Collapse
 
nevodavid profile image
Nevo David

Image description

Collapse
 
nevodavid profile image
Nevo David

Notifications