Introduction
Implementing real-time chat functionality is a common requirement for many web applications, but building it from scratch with WebSocket management and scalability considerations can be quite challenging.
Today, I'll show you how to implement real-time chat surprisingly easily using **Supabase UI (via shadcn CLI) + Next.js**.
TL;DR
The complete code is available here:
https://github.com/tnakayama256/simple-chat
Prerequisites
This article assumes you have completed the following preparations:
- Public URL (Project URL)
- Anon Key
- Service Role Key
Implementation Steps
1. Create a Next.js Application
First, create a new Next.js project:
pnpm create next-app@latest my-chat-app
cd my-chat-app2. Configure Environment Variables
Create a `.env.local` file in the project root and set your Supabase credentials:
NEXT_PUBLIC_SUPABASE_URL=your-project-url
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key**Note**: The service role key is sensitive information and should only be used on the server side, never on the client side.
3. Initialize shadcn/ui
Set up shadcn/ui in your project:
pnpm dlx shadcn@latest initWhen prompted, select your preferred settings. TypeScript, ESLint, and Tailwind CSS configurations will be automatically set up.
4. Install Real-time Chat Component
Install the real-time chat component provided by Supabase UI:
pnpm dlx shadcn@latest add https://supabase.com/ui/r/realtime-chat-nextjs.jsonThis single command installs all the necessary components (RealtimeChat) and dependencies for real-time chat.
5. Implementation Example
// app/chat/page.tsx
import { RealtimeChat } from '@/components/realtime-chat'
export default async function ProtectedPage() {
return (
<div className="flex h-svh w-full max-w-screen-sm mx-auto items-center justify-center gap-2">
<RealtimeChat
roomName="simple-chat-room"
username={data.user.email ?? ''}
/>
</div>
)
}Implementation Points
Security Considerations
Performance Optimization
Customization Possibilities
The `RealtimeChat` component can be customized in the following ways:
Notes
Summary
The combination of Supabase UI and Next.js allows you to implement complex real-time chat functionality in just a few steps. With this approach, you can:
Please try this method and add real-time chat functionality to your projects. If you have any questions during implementation, feel free to contact me (contact@tnakayama.com)