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.
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.
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
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 Router is 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.
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.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
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.
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(`\u26a1: ${socket.id} user just connected!`); socket.on('disconnect', () => { console.log('\ud83d\udd25: 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.
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:
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> );};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.
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.
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(`\u26a1: ${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(`\u26a1: ${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> );};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.
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.
let eventList = [];socketIO.on("connection", (socket) => { console.log(`\u26a1: ${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> );};export default App;
You have finished the basic event scheduling and showing it on the browser 💁🏻♀️
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.
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
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.
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: "", }) .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.
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.
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.
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 running npx novu init
Now let's setup your account and send your first notification\u2753 What is your application name? Devto Clone\u2753 Now lets setup your environment. How would you like to proceed? > Create a free cloud account (Recommended)\u2753 Create your account with: > Sign-in with GitHub\u2753 I accept the Terms and Condidtions (https://novu.co/terms) and have read the Privacy Policy (https://novu.co/privacy) > Yes\u2714\ufe0f 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 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.
/*\ud83d\udc49\ud83c\udffb Run npm install @novu/node in your terminal*/const { Novu, PushProviderIdEnum } = require("@novu/node");const novu = new Novu("");
Send the push notifications request via Novu in the server/index.js file by updating the /api route as below:
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:
async function sendNotification(message) { const subscriberId = ""; await novu.subscribers.identify(subscriberId, { firstName: "", lastName: "", }); await novu.subscribers.setCredentials(subscriberId, PushProviderIdEnum.FCM, { deviceTokens: [""], }); const trigger = await novu.trigger("", { to: { subscriberId, }, /*\ud83d\udc47\ud83c\udffb 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(`\u26a1: ${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(); });});
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.