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 SuperViz Real-time 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 SuperViz Real-time 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.
1mkdir realtime-notifications-server2cd realtime-notifications-server3npm init -y4npm 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.js2import process from "node:process";3import express from "express";4import bodyParser from "body-parser";5import dotenv from "dotenv";6import cors from "cors";78dotenv.config(); // Load environment variables910const app = express(); // Initialize Express application1112app.use(bodyParser.json()); // Use body-parser to parse JSON13app.use(cors()); // Enable CORS1415// Basic route to check server uptime16app.get("/", (req, res) => {17res.send(18JSON.stringify({19uptime: process.uptime(),20})21);22});
- Express App: An Express application is created to handle requests.
- Middlewares:
bodyParser
is used for JSON parsing, andcors
is enabled for cross-origin requests.
3. Implement the Notification Endpoint
Define an endpoint to schedule and send notifications using SuperViz.
1app.post("/notify", (req, res) => {2if (!req.body) {3return res.status(400).send({4status: "error",5message: "Missing body",6});7}89const { channel, message, msToWait } = req.body;1011if (!channel || !message || !msToWait) {12return res.status(400).send({13status: "error",14message: "Missing required fields: channel, message, msToWait",15});16}1718setTimeout(async () => {19const response = await fetch(20`https://api.superviz.com/realtime/${channel}/publish`,21{22method: "POST",23headers: {24"Content-Type": "application/json",25client_id: process.env.VITE_SUPERVIZ_CLIENT_ID,26secret: process.env.VITE_SUPERVIZ_SECRET_KEY,27},28body: JSON.stringify({29name: "new-notification",30data: message,31}),32}33);3435console.log(36`Sending data to ${channel}, message: ${message}`,37response.status38);39}, msToWait);4041res.send({42status: "success",43message: "Notification scheduled",44});45});
- Notify Endpoint: The
/notify
endpoint accepts POST requests to schedule notifications. - Request Validation: Validates the presence of
channel
,message
,msToWait
, androomId
. - Delayed Execution: Uses
setTimeout
to waitmsToWait
milliseconds before sending the notification using the SuperViz API.
4. Start the Server
Launch the server to listen for requests.
1app.listen(3000, () => {2console.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.
1npx create-react-app realtime-notifications-frontend --template typescript2cd realtime-notifications-frontend
2. Install SuperViz SDK and React Toastify
Add the necessary packages to the project.
1npm install @superviz/realtime react-toastify uuid
- @superviz/realtime: SuperViz Real-Time library for integrating real-time synchronization into your application.
- 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.
1npm install -D tailwindcss postcss autoprefixer2npx 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} */2export default {3content: [4"./index.html",5"./src/**/*.{js,ts,jsx,tsx}",6],7theme: {8extend: {},9},10plugins: [],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.
1VITE_SUPERVIZ_API_KEY=YOUR_SUPERVIZ_API_KEY
- Environment Variables: Store the API key securely using
.env
and access it throughimport.meta.env
.
5. Implement the Main App Component
Open src/App.tsx
and set up the main component to handle notifications.
1import { v4 as generateId } from "uuid";2import { useCallback, useEffect, useState } from "react";3import SuperVizRoom, {4Realtime,5RealtimeComponentEvent,6} from "@superviz/sdk";7import { ToastContainer, toast } from "react-toastify";8import "react-toastify/dist/ReactToastify.css";910const apiKey = import.meta.env.VITE_SUPERVIZ_API_KEY as string;11const PARTICIPANT_ID = generateId();1213export default function App() {14const initialized = useRef(false);15const [message, setMessage] = useState("");16const [msToWait, setMsToWait] = useState(1000);1718const initialize = useCallback(async () => {19if (initialized.current) return;2021const realtime = new Realtime(apiKey, {22participant: {23id: PARTICIPANT_ID,24name: "participant-name",25},26debug: true,27});2829initialized.current = true;3031const channel = await realtime.connect("notification-topic");3233channel.subscribe("new-notification", (data) => {34if (typeof data === "string") return;3536toast.info(data.data as string, {37position: "top-right",38autoClose: 3000,39});40});41}, [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 usingreact-toastify
.
6. Implement the Notification Function
Add the logic for sending notifications.
1const notify = useCallback(async () => {2try {3fetch("http://localhost:3000/notify", {4method: "POST",5headers: {6"Content-Type": "application/json",7},8body: JSON.stringify({9roomId: ROOM_ID,10channel: "notification-topic",11message: message,12msToWait: msToWait || 1000,13}),14});1516toast.success("Notification sent!", {17position: "top-right",18autoClose: 1000,19});2021setMessage("");22setMsToWait(1000);23} catch (error) {24toast.error("Failed to send notification!", {25position: "top-right",26autoClose: 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.
1useEffect(() => {2initialize();3}, [initialize]);45return (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">16Schedule a notification to be sent to all participants in the room.17</p>18<hr className="my-5" />1920<label htmlFor="message" className="text-lg font-bold">21Message22</label>23<input24type="text"25id="message"26name="message"27placeholder="Hello, World!"28className="w-full p-3 border border-gray-300 rounded-md"29value={message}30onChange={(e) => setMessage(e.target.value)}31/>32<hr className="my-5" />33<label htmlFor="msToWait" className="text-lg font-bold">34Time to wait (ms)35</label>36<input37type="number"38id="msToWait"39name="msToWait"40placeholder="1000"41className="w-full p-3 border border-gray-300 rounded-md"42min={1000}43value={msToWait}44onChange={(e) => setMsToWait(Number(e.target.value))}45/>46<hr className="my-5" />47<button48type="button"49onClick={notify}50className="bg-purple-400 text-white p-3 rounded-md disabled:bg-gray-300"51disabled={!message || !initialized || msToWait < 1000}52>53Send Notification54</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:
1npm 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.