0Pricing
Supabase Backend as a Service · 강의

실시간 채팅 기능 구축

실시간 관련 지식을 적용하여 메시지를 즉시 전달하는 실용적인 실시간 채팅 애플리케이션을 만듭니다.

실시간 채팅 기능 구축은(는) CoddyKit의 무료 Supabase Backend as a Service 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Supabase Backend as a Service 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Supabase Backend as a Service 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Realtime Chat: The Foundation

Welcome to building a live chat! Instant messaging is a perfect example of where realtime capabilities shine.

Users expect their messages to appear instantly without refreshing. Supabase Realtime makes this surprisingly simple.

In this lesson, we'll connect the dots: sending messages to your database and instantly receiving new messages from others.

Designing Your Chat Messages Table

First, we need a place to store our chat messages. A simple table is all it takes!

We'll create a messages table with columns for the message text, who sent it, and when it was sent.

  • id: Primary Key, unique identifier.
  • text: The message content (type: TEXT).
  • user_id: Who sent the message (type: UUID, linked to auth.users).
  • created_at: When the message was sent (type: TIMESTAMPTZ, default to now()).

Initializing Supabase Client

To interact with Supabase from your app, you'll need to initialize the client library. This sets up the connection to your project.

Make sure you have your Supabase URL and Anon Key ready. (These are covered in earlier lessons.)

import { createClient } from '@supabase/supabase-js';

const supabaseUrl = 'YOUR_SUPABASE_URL';
const supabaseAnonKey = 'YOUR_SUPABASE_ANON_KEY';

const supabase = createClient(supabaseUrl, supabaseAnonKey);

This supabase object will be your gateway to sending and receiving messages.

Sending Messages: The Insert Operation

When a user types a message and hits send, your app needs to store that message in the database.

We'll use the Supabase client's insert() method on our messages table. This adds a new row with the message text and the sender's ID.

It's a straightforward database write operation, just like adding any other data.

Code: Sending a Chat Message

Try running this example. It simulates sending a message to your Supabase messages table.

Remember to replace placeholders with your actual Supabase URL/Key and a valid user_id (e.g., from an authenticated user).

import { createClient } from '@supabase/supabase-js';

// Mock Supabase client for demonstration purposes
// In a real app, use your actual Supabase URL and Anon Key
const supabase = {
  from: (tableName) => ({
    insert: async (data) => {
      console.log(`[DEMO] Attempting to insert into ${tableName}:`);
      console.log(JSON.stringify(data, null, 2));
      // Simulate a successful response
      return { data: data, error: null };
    }
  })
};

async function sendChatMessage(messageText, senderId) {
  const { data, error } = await supabase
    .from('messages')
    .insert([
      { text: messageText, user_id: senderId }
    ]);

  if (error) {
    console.error('Error sending message:', error.message);
  } else {
    console.log('Message sent successfully:', data);
  }
}

// --- Run the example ---
sendChatMessage("Hey there, CoddyKit!", "a1b2c3d4-e5f6-7890-1234-567890abcdef");

Receiving Messages in Realtime

Sending messages is only half the story. The magic of live chat is seeing new messages instantly!

Supabase Realtime allows you to subscribe to changes in your database. We'll listen specifically for new INSERT events on our messages table.

When a new message is inserted by any user, your app will receive a notification and can update the chat display.

Code: Subscribing to New Messages

This code sets up a listener for new messages. When a message is inserted, the callback function will run.

The payload.new object contains the full data of the newly inserted message.

import { createClient } from '@supabase/supabase-js';

// Mock Supabase client for demonstration purposes
const supabase = {
  channel: (channelName) => ({
    on: (eventType, filter, callback) => {
      console.log(`[DEMO] Subscribing to channel "${channelName}" for event "${eventType}" with filter:`, JSON.stringify(filter));
      // Simulate a message arriving after a delay
      setTimeout(() => {
        const mockPayload = {
          eventType: 'INSERT',
          schema: 'public',
          table: 'messages',
          new: { id: 2, text: 'This is a new realtime message!', user_id: 'another-user-id', created_at: new Date().toISOString() },
          old: {}
        };
        console.log("[DEMO] Simulating new message arrival...");
        callback(mockPayload);
      }, 3000); // Simulate message arriving after 3 seconds
      return {
        subscribe: (cb) => {
          console.log("[DEMO] Subscription initiated.");
          // Simulate successful subscription immediately
          cb('SUBSCRIBED');
        }
      };
    }
  })
};

// --- Run the example ---
const chatChannel = supabase.channel('messages_channel');

chatChannel
  .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'messages' }, (payload) => {
    console.log('Realtime: New message received!');
    console.log('Message content:', payload.new.text);
    console.log('From user:', payload.new.user_id);
    // In a real app, you would update your UI here to display the message
  })
  .subscribe((status) => {
    if (status === 'SUBSCRIBED') {
      console.log('Successfully subscribed to new messages!');
    } else {
      console.log('Subscription status:', status);
    }
  });

Displaying Messages in Your UI

Once you receive a new message via the realtime subscription, the next step is to display it in your chat interface.

Typically, you'll take the payload.new object, extract the text, user_id, and created_at, and then dynamically add it to your chat window.

  • Create a new chat bubble/element.
  • Populate it with the message data.
  • Append it to your chat message list.
  • Consider scrolling to the bottom automatically for the best user experience!

Adding User Context & Timestamps

A basic chat works, but a good chat shows who sent what and when.

Since our messages table has a user_id, you can fetch user profiles (e.g., username, avatar) to display alongside messages. This might involve a simple join if you're querying historical messages, or fetching user details separately for realtime messages.

The created_at timestamp automatically provided by Supabase is crucial for ordering messages and showing when they were sent.

Quick Check: Chat Flow

You're building a live chat. What are the two primary Supabase client operations you'll use to make messages appear instantly for all users?

Recap: Your Live Chat Feature

You've successfully built the core of a live chat feature!

We covered:

  • Designing a simple messages table.
  • Sending new messages by inserting data into Supabase.
  • Receiving new messages instantly using Supabase Realtime subscriptions.
  • How to integrate these messages into your app's UI.

This pattern of inserting data and subscribing to changes is fundamental for many realtime applications beyond just chat. Keep exploring!

자주 묻는 질문

“실시간 채팅 기능 구축” 강의는 무료인가요?

네 — “실시간 채팅 기능 구축” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Supabase Backend as a Service 강의 전체를 잠금 해제할 수 있습니다. Supabase Backend as a Service 강의에는 총 4개의 강의가 포함되어 있습니다.

“실시간 채팅 기능 구축”에서 뭘 배우나요?

실시간 관련 지식을 적용하여 메시지를 즉시 전달하는 실용적인 실시간 채팅 애플리케이션을 만듭니다. 브라우저에서 직접 실행하는 실습 코드로 Supabase Backend as a Service을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Supabase Backend as a Service을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Supabase Backend as a Service은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“실시간 채팅 기능 구축” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Supabase Backend as a Service 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Supabase Backend as a Service 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 실시간 구독 이해하기
  2. 테이블 변경 사항 구독하기
  3. 실시간 채팅 기능 구축
  4. 프레즌스 및 브로드캐스트 채널
← Supabase Backend as a Service(으)로 돌아가기