Join a Chat Channel

If you are building an application with Chat features or even a stand-alone Chat app, you can use the Chat Token you obtained in the authentication step to create a Chat Client. With the Chat Client constructor, you can subscribe to multiple channels then send and receive messages in any of those channels.

const chatClient = new Chat.Client({
  token: '<YourJWT>',
});

await chatClient.subscribe([ 'mychannel1', 'mychannel2' ]);
// To listen for incoming messages
chatClient.on('message', (message) => {
  console.log("Received", message.content,
              "on", message.channel,
              "at", message.publishedAt)
});
// To send messages
await chatClient.publish({
  channel: 'mychannel1',
  content: 'hello world'
});
const chatClient = new Chat.Client({
  token: '<YourJWT>',
});

chatClient.subscribe([ 'mychannel1', 'mychannel2' ]).then(() => {
// To listen for incoming messages...
  chatClient.on('message', (message) => {
    console.log("Received", message.content,
              "on", message.channel,
              "at", message.publishedAt)
    });
// To send a message to a Channel...
    chatClient.publish({
    channel: 'mychannel1',
    content: 'hello world'
    });
}).catch(error => {
  console.error('Error', error)
});

The Chat Client token belongs to a single member ID, and can subscribe to multiple channels. You can add the chatClient.on listener at any time, but please note you must successfully subscribe to a channel before chatClient.publish is available.


What’s Next
Did this page help you?