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.

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/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.

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 {
4
Realtime,
5
type RealtimeMessage,
6
type Channel,
7
} from "@superviz/realtime/client";
8
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 = {
5
participantName: string;
6
message: 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.

1
export default function App() {
2
const url = new URL(window.location.href);
3
const name = url.searchParams.get("name") || "Anonymous";
4
5
const participant = useRef({
6
id: generateId(),
7
name: 'participant-name',
8
});
9
const channel = useRef<Channel | null>(null);
10
const initialized = useRef(false);
11
const [message, setMessage] = useState('');
12
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.current) return;
3
initialized.current = true;
4
5
const realtime = new Realtime(apiKey, {
6
participant: participant.current,
7
});
8
9
channel.current = await realtime.connect("message-topic");
10
11
channel.current.subscribe<Message>("message", (data) => {
12
setMessages((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.

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-[#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
<div
10
key={index}
11
className={`${
12
message.participantId === participant.current!.id
13
? "justify-end"
14
: "justify-start"
15
} w-full flex mb-2`}
16
>
17
<div
18
className={`${
19
message.participantId === participant.current!.id
20
? "bg-[#f29ee8]"
21
: "bg-[#baa9ff]"
22
} text-black p-2 rounded-lg max-w-xs`}
23
>
24
<div
25
className={`${
26
message.participantId === participant.current!.id
27
? "text-right"
28
: "text-left"
29
} text-xs text-[#57535f]`}
30
>
31
{message.participantId === participant.current!.id
32
? "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
<input
42
type="text"
43
placeholder="Type your message..."
44
className="flex-1 border rounded-full px-4 py-2 focus:outline-none"
45
value={message}
46
onChange={(e) => setMessage(e.target.value)}
47
/>
48
<button
49
className="bg-purple-400 text-white px-4 py-2 rounded-full disabled:opacity-50"
50
onClick={sendMessage}
51
disabled={!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:

  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.