Building a live-event alert system with React, Socket.io, and Push Notifications 🚀
Tags: javascript, react, programming, webdev
Published: 2022-09-05 14:36:26

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0b95cz38yx3cpg5klaps.gif)

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](https://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](https://novu.co). 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yn90yvsd87tgik03c08v.gif)

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

```bash
mkdir event-scheduler
cd event-scheduler
mkdir client server
```

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

```bash
cd client
npx create-react-app ./
```

Install Socket.io client API and React Router. [React Router](https://reactrouter.com/docs/en/v6) is a JavaScript library that enables us to navigate between pages in a React application.

```bash
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.

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

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

```bash
cd server & npm init -y
```

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

[Express.js](https://expressjs.com/) is a fast, minimalist framework that provides several features for building web applications in Node.js. [CORS](https://www.npmjs.com/package/cors) is a Node.js package that allows communication between different domains.

[Nodemon](https://www.npmjs.com/package/nodemon) is a Node.js tool that automatically restarts the server after detecting file changes, and [Socket.io](https://socket.io/docs/v4/server-api/) allows us to configure a real-time connection on the server.

```bash
npm install express cors nodemon socket.io
```

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

```bash
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.

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

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

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

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.

```jsx
//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');
    });
});
```

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.

```json
//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.

```bash
npm start
```

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

```jsx
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.

```bash
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gg8w1u25d175mwzwczb8.png)

Update the `App.js` file as below:

```jsx
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.

```css
@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.

```jsx
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.

```jsx
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.

```jsx
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.

```jsx
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.

```jsx
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.

```jsx
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.

```jsx
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.

```jsx
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:

```jsx
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 configure [React Toastify](https://www.npmjs.com/package/react-toastify) as below:

```jsx
//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
```

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

```jsx
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`

```jsx
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.

```jsx
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mbm8ghy6v3dh1cvfue07.jpeg)

### Setting up Firebase Cloud Messaging

Go to the [Firebase Console](https://console.firebase.google.com/), 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

```jsx
//👉🏻 In client/src/firebase.js
import { initializeApp } from "firebase/app";

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

// Initialize Firebase
const app = initializeApp(firebaseConfig);
```

Install Firebase to your React project.

```bash
cd client
npm 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/snn47g12rjyww3p3xk22.png)


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

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

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

```bash
cd client/public
touch firebase-messaging-sw.js
```

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

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

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

```jsx
//....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;
```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hdhm5et1opoimi4dt6na.png)

## 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](https://onesignal.com/) or you can implement it yourself.

Navigate into the client folder and create a Novu project by running the code below.

```bash
cd client
npx 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`

```bash
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 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0kzqjnlvgzkwdgcv6avk.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ypsvhodl34y18h9gsrll.png)

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

Edit the template by adding Push to its workflow

![Push](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/haut6mla60cotx888sty.png)

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

Next, install and configure Novu on the server.

```jsx
/*
👉🏻 Run npm install @novu/node in your terminal
*/
const { Novu, PushProviderIdEnum } = require("@novu/node");
const novu = new Novu("<YOUR_API_KEY>");

```

![Api Keys](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0f1m42h1pzlm51pbftz5.png)

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

```jsx
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yw0t0efvoddunwco8zxi.png)

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:

```jsx
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](https://github.com/novuhq/blog/tree/main/event-scheduler-with-push-notifications)

Thank you for reading!

![Love You](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g5ay48mr4p98a2cjj1ty.gif)