apps/ui-library/content/docs/nextjs/realtime-chat.mdx
<BlockItem name="realtime-chat-nextjs" description="Renders a real-time chat interface for users in a shared room." />
The Realtime Chat component provides a complete chat interface that enables users to exchange messages in real-time within a shared room.
This chat component uses Supabase Realtime Broadcast to send and receive messages between connected clients.
Messages sent through Broadcast are:
roomName, which corresponds to a broadcast channelThis design keeps latency extremely low, but it means you should use the onMessage callback if you want to store messages permanently or show chat history on page load.
import { RealtimeChat } from '@/components/realtime-chat'
export default function ChatPage() {
return <RealtimeChat roomName="my-chat-room" username="john_doe" />
}
import { RealtimeChat } from '@/components/realtime-chat'
import { useMessagesQuery } from '@/hooks/use-messages-query'
export default function ChatPage() {
const { data: messages } = useMessagesQuery()
return <RealtimeChat roomName="my-chat-room" username="john_doe" messages={messages} />
}
import { RealtimeChat } from '@/components/realtime-chat'
import { useMessagesQuery } from '@/hooks/use-messages-query'
import { storeMessages } from '@/lib/store-messages'
export default function ChatPage() {
const { data: messages } = useMessagesQuery()
const handleMessage = (messages: ChatMessage[]) => {
// Store messages in your database
await storeMessages(messages)
}
return <RealtimeChat roomName="my-chat-room" username="john_doe" onMessage={handleMessage} />
}
onMessage and messages props| Prop | Type | Description |
|---|---|---|
roomName | string | Unique identifier for the shared chat room. |
username | string | Name of the current user; used to identify message senders. |
onMessage? | (messages: ChatMessage[]) => void | Optional callback to handle messages, useful for persistence. |
messages? | ChatMessage[] | Optional initial messages to display in the chat. |
interface ChatMessage {
id: string
content: string
user: {
name: string
}
createdAt: string
}