In this tutorial, we'll guide you through building a real-time notifications feature using SuperViz, a powerful SDK for real-time communication and data synchronization. Real-time notifications are a critical feature for many applications, enabling instant communication and engagement with users as events unfold.

We'll use SuperViz's Real-Time Data Engine to send and receive notifications, demonstrating how to integrate this functionality into a React application. Although we’ll use a simple example for illustrative purposes, the techniques you’ll learn can be applied to various scenarios such as messaging apps, live updates for e-commerce sites, or alert systems in business applications. Let's dive in!

Prerequisite

To follow this tutorial, you will need a SuperViz account and a developer token. If you already have an account and a developer token, you can move on to the next step.

Create an account

To create an account, go to https://dashboard.superviz.com/register and create an account using either Google or an email/password. It's important to note that when using an email/password, you will receive a confirmation link that you'll need to click to verify your account.

Retrieving a Developer Token

To use the SDK, you’ll need to provide a developer token, as this token is essential for associating SDK requests with your account. You can retrieve both development and production SuperViz tokens from the dashboard..
Copy and save the developer token, as you will need it in the next steps of this tutorial.

Step 1: Setting Up the Server with Express.js

In this tutorial, we'll guide you through building a real-time notification system using SuperViz, a powerful SDK for real-time communication and data synchronization. Real-time notifications are a critical feature for many applications, enabling instant communication and engagement with users as events unfold.

We'll use SuperViz's Real-Time Data Engine to send and receive notifications, demonstrating how to integrate this functionality into a React application. Although we’ll use a simple example for illustrative purposes, the techniques you’ll learn can be applied to various scenarios such as messaging apps, live updates for e-commerce sites, or alert systems in business applications. Let's dive in!

The server will handle incoming notification requests and use SuperViz to send real-time updates to clients.

1. Create a New Project and Install Dependencies

First, set up a new Node.js project and install the necessary packages for the server.

1
mkdir realtime-notifications-server
2
cd realtime-notifications-server
3
npm init -y
4
npm install express body-parser dotenv cors
  • express: A web application framework for setting up the server.
  • body-parser: Middleware to parse incoming JSON request bodies.
  • dotenv: Loads environment variables from a .env file.
  • cors: Middleware to enable Cross-Origin Resource Sharing.

2. Set Up the Express Server

Create a file named server.js and configure the server.

1
// server.js
2
import process from "node:process";
3
import express from "express";
4
import bodyParser from "body-parser";
5
import dotenv from "dotenv";
6
import cors from "cors";
7
8
dotenv.config(); // Load environment variables
9
10
const app = express(); // Initialize Express application
11
12
app.use(bodyParser.json()); // Use body-parser to parse JSON
13
app.use(cors()); // Enable CORS
14
15
// Basic route to check server uptime
16
app.get("/", (req, res) => {
17
res.send(
18
JSON.stringify({
19
uptime: process.uptime(),
20
})
21
);
22
});
  • Express App: An Express application is created to handle requests.
  • Middlewares: bodyParser is used for JSON parsing, and cors is enabled for cross-origin requests.

3. Implement the Notification Endpoint

Define an endpoint to schedule and send notifications using SuperViz.

1
app.post("/notify", (req, res) => {
2
if (!req.body) {
3
return res.status(400).send({
4
status: "error",
5
message: "Missing body",
6
});
7
}
8
9
const { channel, message, msToWait, roomId } = req.body;
10
11
if (!channel || !message || !msToWait || !roomId) {
12
return res.status(400).send({
13
status: "error",
14
message: "Missing required fields: channel, message, msToWait, roomId",
15
});
16
}
17
18
setTimeout(async () => {
19
const response = await fetch(
20
`https://nodeapi.superviz.com/realtime/${roomId}/${channel}/publish`,
21
{
22
method: "POST",
23
headers: {
24
"Content-Type": "application/json",
25
apiKey: process.env.VITE_SUPERVIZ_API_KEY,
26
},
27
body: JSON.stringify({
28
name: "new-notification",
29
data: message,
30
}),
31
}
32
);
33
34
console.log(
35
`Sending data to ${channel}, message: ${message}`,
36
response.status
37
);
38
}, msToWait);
39
40
res.send({
41
status: "success",
42
message: "Notification scheduled",
43
});
44
});
  • Notify Endpoint: The /notify endpoint accepts POST requests to schedule notifications.
  • Request Validation: Validates the presence of channel, message, msToWait, and roomId.
  • Delayed Execution: Uses setTimeout to wait msToWait milliseconds before sending the notification using the SuperViz API.

4. Start the Server

Launch the server to listen for requests.

1
app.listen(3000, () => {
2
console.log("Server is running on <http://localhost:3000>");
3
});
  • Server Listening: The server listens on port 3000 and logs a confirmation message when it's running.

Step 2: Setting Up the Frontend with React

The frontend will display notifications in real time using React and SuperViz.

1. Create a New React Project

Initialize a new React application using Create React App with TypeScript.

1
npx create-react-app realtime-notifications-frontend --template typescript
2
cd realtime-notifications-frontend

2. Install SuperViz SDK and React Toastify

Add the necessary packages to the project.

1
npm install @superviz/sdk react-toastify uuid
  • @superviz/sdk: SDK for real-time collaboration features.
  • react-toastify: Library for showing notifications as toast messages.
  • uuid: Library for generating unique identifiers.

3. Configure tailwind

In this tutorial, we'll use the Tailwind css framework. First, install the tailwind package.

1
npm install -D tailwindcss postcss autoprefixer
2
npx tailwindcss init -p

We then need to configure the template path. Open tailwind.config.js in the root of the project and insert the following code.

1
/** @type {import('tailwindcss').Config} */
2
export default {
3
content: [
4
"./index.html",
5
"./src/**/*.{js,ts,jsx,tsx}",
6
],
7
theme: {
8
extend: {},
9
},
10
plugins: [],
11
}

Then we need to add the tailwind directives to the global CSS file. (src/index.css)

1
@tailwind base;
2
@tailwind components;
3
@tailwind utilities;

4. Set Up Environment Variables

Create a .env file in the frontend directory and add your SuperViz API key.

1
VITE_SUPERVIZ_API_KEY=YOUR_SUPERVIZ_API_KEY
  • Environment Variables: Store the API key securely using .env and access it through import.meta.env.

5. Implement the Main App Component

Open src/App.tsx and set up the main component to handle notifications.

1
import { v4 as generateId } from "uuid";
2
import { useCallback, useEffect, useState } from "react";
3
import SuperVizRoom, {
4
Realtime,
5
RealtimeComponentEvent,
6
} from "@superviz/sdk";
7
import { ToastContainer, toast } from "react-toastify";
8
import "react-toastify/dist/ReactToastify.css";
9
10
const apiKey = import.meta.env.VITE_SUPERVIZ_API_KEY as string;
11
const ROOM_ID = generateId();
12
13
export default function App() {
14
const [initialized, setInitialized] = useState(false);
15
const [message, setMessage] = useState("");
16
const [msToWait, setMsToWait] = useState(1000);
17
18
const initialize = useCallback(async () => {
19
if (initialized) return;
20
21
const superviz = await SuperVizRoom(apiKey, {
22
roomId: ROOM_ID,
23
participant: {
24
id: generateId(),
25
name: "participant-name",
26
},
27
group: {
28
id: "realtime-notifications",
29
name: "realtime-notifications",
30
},
31
});
32
33
const realtime = new Realtime();
34
superviz.addComponent(realtime);
35
setInitialized(true);
36
37
realtime.subscribe(RealtimeComponentEvent.REALTIME_STATE_CHANGED, () => {
38
const channel = realtime.connect("notification-topic");
39
40
channel.subscribe("new-notification", (data) => {
41
console.log("new event:", data);
42
43
if (typeof data === "string") return;
44
45
toast.info(data.data as string, {
46
position: "top-right",
47
autoClose: 3000,
48
});
49
});
50
});
51
}, [initialized]);
  • State Management: The component uses useState to manage the state for initialization, message, and delay time.
  • SuperViz Initialization: Connects to the SuperViz room using the API key, room ID, and participant details.
  • Realtime Subscription: Subscribes to new-notification events and displays the notification using react-toastify.

6. Implement the Notification Function

Add the logic for sending notifications.

1
const notify = useCallback(async () => {
2
try {
3
fetch("http://localhost:3000/notify", {
4
method: "POST",
5
headers: {
6
"Content-Type": "application/json",
7
},
8
body: JSON.stringify({
9
roomId: ROOM_ID,
10
channel: "notification-topic",
11
message: message,
12
msToWait: msToWait || 1000,
13
}),
14
});
15
16
toast.success("Notification sent!", {
17
position: "top-right",
18
autoClose: 1000,
19
});
20
21
setMessage("");
22
setMsToWait(1000);
23
} catch (error) {
24
toast.error("Failed to send notification!", {
25
position: "top-right",
26
autoClose: 1000,
27
});
28
}
29
}, [message, msToWait]);
  • Notify Function: Sends a POST request to the server to schedule the notification.
  • Success/Failure Toasts: Displays a toast message indicating whether the notification was sent successfully or failed.

7. Render the UI Components

Complete the App component by rendering the user interface.

1
useEffect(() => {
2
initialize();
3
}, [initialize]);
4
5
return (
6
<>
7
<ToastContainer />
8
<div className="w-full h-full bg-gray-200 flex items-center justify-center flex-col">
9
<header className="w-full p-5 bg-purple-400 flex items-center justify-between">
10
<h1 className="text-white text-2xl font-bold">Realtime Notifications</h1>
11
</header>
12
<main className="flex-1 p-20 flex w-full gap-2 items-center justify-center">
13
<form>
14
<h2 className="text-xl font-bold">Send Notification</h2>
15
<p className="text-gray-500">
16
Schedule a notification to be sent to all participants in the room.
17
</p>
18
<hr className="my-5" />
19
20
<label htmlFor="message" className="text-lg font-bold">
21
Message
22
</label>
23
<input
24
type="text"
25
id="message"
26
name="message"
27
placeholder="Hello, World!"
28
className="w-full p-3 border border-gray-300 rounded-md"
29
value={message}
30
onChange={(e) => setMessage(e.target.value)}
31
/>
32
<hr className="my-5" />
33
<label htmlFor="msToWait" className="text-lg font-bold">
34
Time to wait (ms)
35
</label>
36
<input
37
type="number"
38
id="msToWait"
39
name="msToWait"
40
placeholder="1000"
41
className="w-full p-3 border border-gray-300 rounded-md"
42
min={1000}
43
value={msToWait}
44
onChange={(e) => setMsToWait(Number(e.target.value))}
45
/>
46
<hr className="my-5" />
47
<button
48
type="button"
49
onClick={notify}
50
className="bg-purple-400 text-white p-3 rounded-md disabled:bg-gray-300"
51
disabled={!message || !initialized || msToWait < 1000}
52
>
53
Send Notification
54
</button>
55
</form>
56
</main>
57
</div>
58
</>
59
);
  • UI Structure: The UI contains an input for the message and delay time, and a button to send notifications.
  • Form Validation: The button is disabled if the message is empty, the system is not initialized, or the delay time is less than 1000ms.

Step 3: Running the Application

To start the application, run this command in the terminal:

1
npm run dev

This command will start both the server and the frontend application.

You can access the frontend application at http://localhost:5173 and the server at http://localhost:3000.

Summary

In this tutorial, we've built a real-time notification system using SuperViz, Express.js, and React. The server schedules and sends notifications to clients using SuperViz's real-time API. The frontend subscribes to notification events, displaying them as toast messages. By following these steps, you can customize the notification system to handle different types of messages, add more features, and deploy it to a production environment.

Feel free to refer to the full code in the GitHub repository for more details.