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 Create React App with TypeScript.

1
npm create vite@latest realtime-chat -- --template react-ts
2
cd realtime-chat

2. Install Required Libraries

Next, install the necessary libraries for our project:

1
npm install @superviz/sdk uuid react-icons
  • @superviz/sdk: For integrating real-time communication features.
  • 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.

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 your project root and add your SuperViz developer key. This key will be used to authenticate your application with SuperViz services.

1
VITE_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.

1
import { v4 as generateId } from 'uuid';
2
import { useCallback, useEffect, useState, useRef } from "react";
3
import SuperVizRoom, { Realtime, RealtimeComponentEvent, RealtimeMessage } from '@superviz/sdk';
4
import { 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.

1
const apiKey = import.meta.env.VITE_SUPERVIZ_API_KEY as string;
2
const ROOM_ID = 'realtime-chat';
3
4
type Message = RealtimeMessage & {
5
data: {
6
participantName: string;
7
message: string;
8
}
9
}

Explanation:

  • apiKey: Retrieves the SuperViz API key from environment variables.
  • ROOM_ID: Defines the room ID for the SuperViz session.
  • Message: A type that extends 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.

1
export default function App() {
2
const participant = useRef({
3
id: generateId(),
4
name: 'participant-name',
5
});
6
const channel = useRef<any | null>(null);
7
const [initialized, setInitialized] = useState(false);
8
const [message, setMessage] = useState('');
9
const [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.

1
const initialize = useCallback(async () => {
2
if (initialized) return;
3
4
const superviz = await SuperVizRoom(apiKey, {
5
roomId: ROOM_ID,
6
participant: participant.current,
7
group: {
8
id: 'realtime-chat',
9
name: 'realtime-chat',
10
},
11
});
12
13
const realtime = new Realtime();
14
superviz.addComponent(realtime);
15
setInitialized(true);
16
17
realtime.subscribe(RealtimeComponentEvent.REALTIME_STATE_CHANGED, () => {
18
channel.current = realtime.connect('message-topic');
19
20
channel.current.subscribe('message', (data: Message) => {
21
setMessages((prev) => [...prev, data].sort((a, b) => a.timestamp - b.timestamp));
22
});
23
});
24
}, [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.

1
const sendMessage = useCallback(() => {
2
if (!channel.current) return;
3
4
channel.current.publish('message', {
5
message,
6
participantName: participant.current!.name,
7
});
8
9
setMessage('');
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.

1
useEffect(() => {
2
initialize();
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.

1
return (
2
<div className='w-full h-full bg-gray-200 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 overflow-hidden'>
7
<div className='flex-1 bg-gray-300 w-full p-2'>
8
{
9
messages.map((message) => (
10
<div className={`${message.participantId === participant.current!.id ? 'justify-end' : 'justify-start'} w-full flex mb-2`}>
11
<div className={`${message.participantId === participant.current!.id ? 'bg-purple-200' : 'bg-blue-300'} text-black p-2 rounded-lg max-w-xs`}>
12
<div className={`${message.participantId === participant.current!.id ? 'text-right' : 'text-left'} text-xs text-gray-500`}>
13
{message.participantId === participant.current!.id ? 'You' : message.data.participantName}
14
</div>
15
{message.data.message}
16
</div>
17
</div>
18
))
19
}
20
</div>
21
<div className='p-2 flex items-center justify-between gap-2 w-full'>
22
<input
23
type="text"
24
placeholder="Type your message..."
25
className="flex-1 border rounded-full px-4 py-2 focus:outline-none"
26
value={message}
27
onChange={(e) => setMessage(e.target.value)}
28
/>
29
<button
30
className='bg-purple-400 text-white px-4 py-2 rounded-full disabled:opacity-50'
31
onClick={sendMessage}
32
disabled={!message || !channel.current}
33
>
34
<IoMdSend />
35
</button>
36
</div>
37
</main>
38
</div>
39
)

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:

  1. App.tsx:
    • Initializes SuperViz and sets up real-time chat functionality.
    • Handles sending and receiving chat messages in real-time.
  2. Chat Interface: Displays messages in a chat bubble format and provides an input field and send button for users to send messages.
  3. 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:

1
npm 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.