Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for How to build a notifications feature with React
SuperViz profile imagePachi 🥑
Pachi 🥑 forSuperViz

Posted on • Edited on • Originally published atsuperviz.com

     

How to build a notifications feature with React

Hello everyone 👋🏼

In today's tutorial, we'll guide you through building a real-time notifications feature using SuperViz, a powerful platform 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

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

Create an account

To create an account, go tohttps://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

You’ll need to provide a developer token to use the platform, as this token is essential for associating platform requests with your account. You can retrieve development and production SuperViz tokens fromthe 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 platform 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'sReal-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.

mkdirrealtime-notifications-servercdrealtime-notifications-servernpminit-ynpminstallexpressbody-parserdotenvcors
Enter fullscreen modeExit fullscreen mode
  • 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 namedserver.js and configure the server.

// server.jsimportprocessfrom"node:process";importexpressfrom"express";importbodyParserfrom"body-parser";importdotenvfrom"dotenv";importcorsfrom"cors";dotenv.config();// Load environment variablesconstapp=express();// Initialize Express applicationapp.use(bodyParser.json());// Use body-parser to parse JSONapp.use(cors());// Enable CORS// Basic route to check server uptimeapp.get("/",(req,res)=>{res.send(JSON.stringify({uptime:process.uptime(),}));});
Enter fullscreen modeExit fullscreen mode
  • 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.

app.post("/notify",(req,res)=>{if(!req.body){returnres.status(400).send({status:"error",message:"Missing body",});}const{channel,message,msToWait}=req.body;if(!channel||!message||!msToWait){returnres.status(400).send({status:"error",message:"Missing required fields: channel, message, msToWait",});}setTimeout(async()=>{constresponse=awaitfetch(`https://api.superviz.com/realtime/${channel}/publish`,{method:"POST",headers:{"Content-Type":"application/json",client_id:process.env.VITE_SUPERVIZ_CLIENT_ID,secret:process.env.VITE_SUPERVIZ_SECRET_KEY,},body:JSON.stringify({name:"new-notification",data:message,}),});console.log(`Sending data to${channel}, message:${message}`,response.status);},msToWait);res.send({status:"success",message:"Notification scheduled",});});
Enter fullscreen modeExit fullscreen mode
  • Notify Endpoint: The/notify endpoint accepts POST requests to schedule notifications.
  • Request Validation: Validates the presence ofchannel,message,msToWait, androomId.
  • Delayed Execution: UsessetTimeout to waitmsToWait milliseconds before sending the notification using the SuperViz API.

4. Start the Server

Launch the server to listen for requests.

app.listen(3000,()=>{console.log("Server is running on <http://localhost:3000>");});
Enter fullscreen modeExit fullscreen mode
  • 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.

npxcreate-react-apprealtime-notifications-frontend--templatetypescriptcdrealtime-notifications-frontend
Enter fullscreen modeExit fullscreen mode

2. Install SuperViz SDK and React Toastify

Add the necessary packages to the project.

npminstall@superviz/sdk react-toastify uuid
Enter fullscreen modeExit fullscreen mode
  • @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 theTailwind css framework. First, install the tailwind package.

npminstall-Dtailwindcsspostcssautoprefixernpxtailwindcssinit-p
Enter fullscreen modeExit fullscreen mode

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

/** @type  {import('tailwindcss').Config} */sexportdefault{content:["./index.html","./src/**/*.{js,ts,jsx,tsx}",],theme:{extend:{},},plugins:[],}
Enter fullscreen modeExit fullscreen mode

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

@tailwindbase;@tailwindcomponents;@tailwindutilities;
Enter fullscreen modeExit fullscreen mode

4. Set Up Environment Variables

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

VITE_SUPERVIZ_API_KEY=YOUR_SUPERVIZ_API_KEY
Enter fullscreen modeExit fullscreen mode
  • Environment Variables: Store the API key securely using.env and access it throughimport.meta.env.

5. Implement the Main App Component

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

import{v4asgenerateId}from"uuid";import{useCallback,useEffect,useState}from"react";importSuperVizRoom,{Realtime,RealtimeComponentEvent,}from"@superviz/sdk";import{ToastContainer,toast}from"react-toastify";import"react-toastify/dist/ReactToastify.css";constapiKey=import.meta.env.VITE_SUPERVIZ_API_KEYasstring;constPARTICIPANT_ID=generateId();exportdefaultfunctionApp(){constinitialized=useRef(false);const[message,setMessage]=useState("");const[msToWait,setMsToWait]=useState(1000);constinitialize=useCallback(async()=>{if(initialized.current)return;constrealtime=newRealtime(apiKey,{participant:{id:PARTICIPANT_ID,name:"participant-name",},debug:true,});initialized.current=true;constchannel=awaitrealtime.connect("notification-topic");channel.subscribe("new-notification",(data)=>{if(typeofdata==="string")return;toast.info(data.dataasstring,{position:"top-right",autoClose:3000,});});},[initialized]);
Enter fullscreen modeExit fullscreen mode
  • State Management: The component usesuseState 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 tonew-notification events and displays the notification usingreact-toastify.

6. Implement the Notification Function

Add the logic for sending notifications.

constnotify=useCallback(async()=>{try{fetch("http://localhost:3000/notify",{method:"POST",headers:{"Content-Type":"application/json",},body:JSON.stringify({roomId:ROOM_ID,channel:"notification-topic",message:message,msToWait:msToWait||1000,}),});toast.success("Notification sent!",{position:"top-right",autoClose:1000,});setMessage("");setMsToWait(1000);}catch(error){toast.error("Failed to send notification!",{position:"top-right",autoClose:1000,});}},[message,msToWait]);
Enter fullscreen modeExit fullscreen mode
  • 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 theApp component by rendering the user interface.

useEffect(()=>{initialize();},[initialize]);return(<><ToastContainer/><divclassName="w-full h-full bg-gray-200 flex items-center justify-center flex-col"><headerclassName="w-full p-5 bg-purple-400 flex items-center justify-between"><h1className="text-white text-2xl font-bold">RealtimeNotifications</h1></header><mainclassName="flex-1 p-20 flex w-full gap-2 items-center justify-center"><form><h2className="text-xl font-bold">SendNotification</h2><pclassName="text-gray-500">Scheduleanotificationtobesenttoallparticipantsintheroom.</p><hrclassName="my-5"/><labelhtmlFor="message"className="text-lg font-bold">Message</label><inputtype="text"id="message"name="message"placeholder="Hello, World!"className="w-full p-3 border border-gray-300 rounded-md"value={message}onChange={(e)=>setMessage(e.target.value)}/><hrclassName="my-5"/><labelhtmlFor="msToWait"className="text-lg font-bold">Timetowait(ms)</label><inputtype="number"id="msToWait"name="msToWait"placeholder="1000"className="w-full p-3 border border-gray-300 rounded-md"min={1000}value={msToWait}onChange={(e)=>setMsToWait(Number(e.target.value))}/><hrclassName="my-5"/><buttontype="button"onClick={notify}className="bg-purple-400 text-white p-3 rounded-md disabled:bg-gray-300"disabled={!message||!initialized||msToWait<1000}>SendNotification</button></form></main></div></>);
Enter fullscreen modeExit fullscreen mode
  • 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:

npm run dev
Enter fullscreen modeExit fullscreen mode

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

You can access the frontend application athttp://localhost:5173 and the server athttp://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 theGitHub repository for more details.


Join us: SuperViz Hackathon 2.0: AI meets RealTime

Get ready to participate in our Super Hackathon 2.0 this October to showcase your innovative real-time AI communication solutions! Hosted by SuperViz and with $5,000 in prizes up for grabs, we challenge you to integrate AI with SuperViz's real-time platform, pushing the boundaries of interactive communication.

Ready to join?Visit the Super Hackathon 2.0 website to register and stay updated.

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
devanshu profile image
Devanshu
  • Joined

Great explanation!
Can you please elaborate how this implementation can be better than adopting Web Socket?

CollapseExpand
 
vtnorton profile image
Vitor Norton
Developer Advocate @ SuperViz | tweets sobre cotidiano de trabalho em tech e as vezes mitologia | lives na twitch | opiniões somente minhas
  • Location
    São Paulo, SP
  • Pronouns
    Ele/Dele/He/Him
  • Work
    Developer Advocate @ SuperViz
  • Joined

It runs Web Sockets behind, but the advantage is to let SuperViz manages all infrastructure, and to make it easier to implement.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

SuperViz is an AI-powered Video SDK that enables developers to integrate real-time communication into web applications. Our platform accelerates development with reliable, scalable infrastructure and a straightforward low-code approach.

More fromSuperViz

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp