Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 5, 2022 02:36 pm GMT

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.iois 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-schedulercd event-schedulermkdir client server

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

cd clientnpx create-react-app ./

Install Socket.io client API and React Router.React Routeris a JavaScript library that enables us to navigate between pages in a React application.

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

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

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

cd server & npm init -y

Install Express.js, CORS, Nodemon, and Socket.io Server API.

Express.jsis a fast, minimalist framework that provides several features for building web applications in Node.js.CORSis a Node.js package that allows communication between different domains.

Nodemonis a Node.js tool that automatically restarts the server after detecting file changes, andSocket.ioallows us to configure a real-time connection on the server.

npm install express cors nodemon socket.io

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

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

//index.jsconst 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}`);});

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 importsconst 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}`);});

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() blocksocketIO.on('connection', (socket) => {    console.log(`: ${socket.id} user just connected!`);    socket.on('disconnect', () => {      console.log(': A user disconnected');    });});

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"  },

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

npm start

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;

Start the React.js server.

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

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;

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;}

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;

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;

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;

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;

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;

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();    });});

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();    });});

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;

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;

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 configureReact Toastify as below:

//In App.js fileimport 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 importsimport "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

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;

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();    });});

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;

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 theFirebase 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.jsimport { initializeApp } from "firebase/app";const firebaseConfig = {    apiKey: "...",    authDomain: "...",    projectId: "...",    storageBucket: "...",    messagingSenderId: "...",    appId: "...",};// Initialize Firebaseconst app = initializeApp(firebaseConfig);

Install Firebase to your React project.

cd clientnpm 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.

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 Firebaseconst firebaseApp = initializeApp(firebaseConfig);//Access Firebase cloud messagingconst 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 serverexport const onMessageListener = () =>    new Promise((resolve) => {        onMessage(messaging, (payload) => {            console.log(payload);            resolve(payload);        });    });

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

cd client/publictouch firebase-messaging-sw.js

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

// Scripts for firebase and firebase messagingimportScripts(    "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 messagingconst 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);});

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

//....other imports// Import the functions from the Firebase.js fileimport { 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;

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 clientnpx 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 runningnpx 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

Visit the demo web pagehttp://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>");

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);});

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();    });});

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


Original Link: https://dev.to/novu/building-a-live-event-alert-system-with-react-socketio-and-push-notifications-2jg5

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To