In this tutorial, we will guide you through building a real-time chat application using SuperViz. Real-time chat is a crucial feature for modern web applications, enabling users to communicate instantly with each other. Whether you're building a collaborative platform, customer support tool, or social networking site, adding real-time chat enhances user interaction and engagement.
We'll demonstrate how to set up a simple chat interface where participants can send and receive messages in real-time. By the end of this tutorial, you'll have a fully functional chat application that you can extend and customize to meet your specific needs.
Let's get started!
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: Set Up Your React Application
To begin, you'll need to set up a new React project where we will integrate SuperViz for real-time communication.
1. Create a New React Project
First, create a new React application using Vite with TypeScript.
1npm create vite@latest realtime-chat -- --template react-ts2cd realtime-chat
2. Install Required Libraries
Next, install the necessary libraries for our project:
1npm install @superviz/realtime uuid react-icons
- @superviz/realtime: SuperViz Real-Time library for integrating real-time synchronization into your application.
- uuid: A library for generating unique identifiers, useful for creating unique participant IDs.
- react-icons: A library for including icons in React applications, used here for the send button icon.
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 your project root and add your SuperViz developer key. This key will be used to authenticate your application with SuperViz services.
1VITE_SUPERVIZ_API_KEY=YOUR_SUPERVIZ_DEVELOPER_KEY
Step 2: Implement the Main Application
In this step, we'll implement the main application logic to initialize SuperViz and handle real-time chat messages.
1. Implement the App Component
Open src/App.tsx
and set up the main application component using SuperViz to manage the chat functionality.
1import { v4 as generateId } from "uuid";2import { useCallback, useEffect, useState, useRef } from "react";3import {4Realtime,5type RealtimeMessage,6type Channel,7} from "@superviz/realtime/client";8import { IoMdSend } from "react-icons/io";
Explanation:
- Imports: Import necessary components from React, SuperViz, UUID, and React Icons for managing state, initializing SuperViz, and rendering the chat interface.
2. Define Constants
Define constants for the API key, room ID, and message types.
1const apiKey = import.meta.env.VITE_SUPERVIZ_API_KEY as string;2const ROOM_ID = 'realtime-chat';34type Message = {5participantName: string;6message: string;7};
Explanation:
- apiKey: Retrieves the SuperViz API key from environment variables.
- ROOM_ID: Defines the room ID for the SuperViz session.
- Message: A type that will be used to extend RealtimeMessage to include participant name and message content.
3. Create the App Component
Set up the main App
component and initialize state variables and references.
1export default function App() {2const url = new URL(window.location.href);3const name = url.searchParams.get("name") || "Anonymous";45const participant = useRef({6id: generateId(),7name: 'participant-name',8});9const channel = useRef<Channel | null>(null);10const initialized = useRef(false);11const [message, setMessage] = useState('');12const [messages, setMessages] = useState<Message[]>([]);
Explanation:
- participant: Stores the current participant's ID and name using
useRef
. - channel: Stores the reference to the real-time communication channel.
- initialized: Tracks whether SuperViz has been initialized.
- message & messages: Manages the current message input and the list of chat messages.
4. Initialize SuperViz
Create a function to initialize SuperViz and set up real-time message handling.
1const initialize = useCallback(async () => {2if (initialized.current) return;3initialized.current = true;45const realtime = new Realtime(apiKey, {6participant: participant.current,7});89channel.current = await realtime.connect("message-topic");1011channel.current.subscribe<Message>("message", (data) => {12setMessages((prev) =>13[...prev, data].sort((a, b) => a.timestamp - b.timestamp)14);15});16}, [initialized]);
Explanation:
- initialize: Initializes SuperViz, sets up the real-time component, and subscribes to the message topic.
- Realtime: Handles real-time communication for the chat.
- channel.current: Stores the connection to the 'message-topic' channel, where messages are published and subscribed.
5. Handle Sending Messages
Create a function to send messages to the chat.
1const sendMessage = useCallback(() => {2if (!channel.current) return;34channel.current.publish('message', {5message,6participantName: participant.current!.name,7});89setMessage('');10}, [message]);
Explanation:
- sendMessage: Publishes the current message to the 'message-topic' channel and resets the message input.
6. Use Effect Hook for Initialization
Use the useEffect
hook to trigger the initialize
function on component mount.
1useEffect(() => {2initialize();3}, [initialize]);
Explanation:
- useEffect: Calls the
initialize
function once when the component mounts, setting up the SuperViz environment and real-time chat.
Step 3: Render the Chat Interface
Finally, return the JSX structure for rendering the chat interface.
1return (2<div className="w-full h-full bg-[#e9e5ef] flex items-center justify-center flex-col">3<header className="w-full p-5 bg-purple-400 flex items-center justify-between">4<h1 className="text-white text-2xl font-bold">Realtime Chat</h1>5</header>6<main className="flex-1 flex w-full flex-col justify-between overflow-hidden">7<div className="bg-[#e9e5ef] w-full p-2 overflow-auto">8{messages.map((message, index) => (9<div10key={index}11className={`${12message.participantId === participant.current!.id13? "justify-end"14: "justify-start"15} w-full flex mb-2`}16>17<div18className={`${19message.participantId === participant.current!.id20? "bg-[#f29ee8]"21: "bg-[#baa9ff]"22} text-black p-2 rounded-lg max-w-xs`}23>24<div25className={`${26message.participantId === participant.current!.id27? "text-right"28: "text-left"29} text-xs text-[#57535f]`}30>31{message.participantId === participant.current!.id32? "You"33: message.data.participantName}34</div>35{message.data.message}36</div>37</div>38))}39</div>40<div className="p-2 flex items-center justify-between gap-2 w-full h-[58px]">41<input42type="text"43placeholder="Type your message..."44className="flex-1 border rounded-full px-4 py-2 focus:outline-none"45value={message}46onChange={(e) => setMessage(e.target.value)}47/>48<button49className="bg-purple-400 text-white px-4 py-2 rounded-full disabled:opacity-50"50onClick={sendMessage}51disabled={!message || !channel.current}52>53<IoMdSend />54</button>55</div>56</main>57</div>58)
Explanation:
- Chat Interface: Displays the chat messages and an input field with a send button. Messages are styled differently based on whether they are sent by the current participant or others.
Step 4: Understanding the Project Structure
Here's a quick overview of how the project structure supports a real-time chat application:
App.tsx
:- Initializes SuperViz and sets up real-time chat functionality.
- Handles sending and receiving chat messages in real-time.
- Chat Interface: Displays messages in a chat bubble format and provides an input field and send button for users to send messages.
- Real-Time Communication: Manages real-time communication between participants using SuperViz.
Step 5: Running the Application
1. Start the React Application
To run your application, use the following command in your project directory:
1npm run dev
This command will start the development server and open your application in the default web browser. You can interact with the chat interface and see messages in real-time as other participants join.
2. Test the Application
- Real-Time Messaging: Open the application in multiple browser windows or tabs to simulate multiple participants and verify that messages are sent and received in real-time.
- Collaborative Interaction: Test the responsiveness of the application by sending messages and observing how the chat updates for all participants.
Summary
In this tutorial, we built a real-time chat application using SuperViz. We configured a React application to handle real-time messaging, enabling multiple users to communicate seamlessly. This setup can be extended and customized to fit various scenarios where real-time communication is essential.
Feel free to explore the full code and further examples in the GitHub repository for more details.