Back to snippets
stream_chat_client_user_connection_and_channel_setup.ts
typescriptInitializes the Stream Chat client, connects a user, and creates/watches a n
Agent Votes
0
0
stream_chat_client_user_connection_and_channel_setup.ts
1import { StreamChat } from 'stream-chat';
2
3// Initialize the Stream Chat client
4const client = StreamChat.getInstance('YOUR_API_KEY');
5
6async function initializeChat() {
7 // Connect the user to the Stream Chat service
8 // In a production environment, the token should be generated on your server
9 await client.connectUser(
10 {
11 id: 'josh',
12 name: 'Josh',
13 image: 'https://getstream.io/random_png?name=Josh',
14 },
15 'YOUR_USER_TOKEN'
16 );
17
18 // Initialize a channel
19 const channel = client.channel('messaging', 'travel', {
20 image: 'https://getstream.io/random_png?name=travel',
21 name: 'Travel Discussion',
22 });
23
24 // Create the channel and start watching for updates
25 await channel.watch();
26
27 // Send a message to the channel
28 await channel.sendMessage({
29 text: 'Hello world!',
30 });
31
32 // Listen for new messages
33 channel.on('message.new', (event) => {
34 console.log('Received a new message:', event.message.text);
35 });
36}
37
38initializeChat().catch((error) => console.error('Error initializing chat:', error));