For AI agents: Find a documentation index at https://talkjs.com/llms.txt (full content at https://talkjs.com/llms-full.txt). Get a markdown version of any page by appending .md to its URL path.

Create a group chat

Build a group chat with three or more participants.

View as Markdown

Build on your first TalkJS chat by creating a new conversation for Frank, Nina, and Juliana.

Prerequisites

Follow the getting-started guide for React or Next.js until you can open the conversation between Frank and Nina. Use the same test app and keep browser synchronization enabled for users and conversations.

Create a group conversation

In your existing Chat component, change conversationId from 'new_conversation' to 'project_group_chat'. The new ID gives the group its own message history, and the existing chatbox already uses that variable to select which conversation to display.

Replace the existing useEffect with this one. Keep userId set to 'frank' and otherUserId set to 'nina'.

useEffect(() => {
  async function createGroupChat() {
    await session.currentUser.createIfNotExists({ name: 'Frank' });
    await session.user(otherUserId).createIfNotExists({ name: 'Nina' });
    await session.user('juliana').createIfNotExists({ name: 'Juliana' });

    const conversation = session.conversation(conversationId);
    await conversation.createIfNotExists({ subject: 'Project chat' });
    await conversation.participant(otherUserId).createIfNotExists();
    await conversation.participant('juliana').createIfNotExists();
  }

  createGroupChat();
}, [session, conversationId, otherUserId]);

Creating the conversation also adds Frank, the current user. Membership is specific to each conversation, so Nina needs to join the new group even though she already belongs to the original chat. The effect creates Juliana's user record and waits for the conversation to exist before adding Nina and Juliana.

Try the group chat

Send a message in Frank's chatbox. To try it as Juliana, render a second chatbox with the same appId and conversationId and set its userId prop to "juliana". You should see Frank's message and be able to reply as Juliana. If you're using an Inbox, pass the group conversation ID as selectedConversationId.

Next steps

In your actual app, you should only run membership changes once a group is created or when someone new is added. Running the participant calls on every visit would re-add participants who have left or been removed.

Before going live, enable authentication. If it's already enabled, authenticate the user's session before making Data API requests or mounting Components. Enforce membership rules on your backend if users shouldn't be able to change membership directly, and configure browser synchronization accordingly.