Search code examples
node.jsreactjstwiliouse-effecttwilio-programmable-chat

Twilio Programmable Chat getChannelByUniqueName throws "Forbidden" Error


After creating a channel in my backend service, I am trying to join the channel in my react frontend in an useEffect hook like this:

const initChat = async () => {

    const chatClient = await Client.create(props.token);
    const channel = await chatClient.getChannelByUniqueName(props.room);

    if (channel) {
      if (channel.status !== "joined") {
        chatClient.on("channelJoined", () => {
          registerChannelListeners(channel);
        });

        await channel.join();
      } else {
        registerChannelListeners(channel);
      }

      setChannel(channel);
      setMessages((await channel?.getMessages()).items);
    }
  };
}

When initially navigating to the page, the error

upstream.js?a850:136 Uncaught (in promise) Error: Forbidden
    at Upstream.actualSend (upstream.js?a850:136)

gets thrown sporadically.

On reloading the page, everything works fine.

The problematic line seems to be:

const channel = await chatClient.getChannelByUniqueName(props.room);

As no further code gets executed. token and room are both assigned with valid values.

In the decoded socket messages, this error message is sent from twilio:

{"method":"reply"...,"http_status":{"code":403,"status":"Forbidden"}}
{"status":403,"message":"User not member of channel","code":50400}

although both participants are invited via the backend with this function:

inviteParticipantToChannel(participant: Participant, channelSid: string) {
    this.logger.log(
      `Inviting paricipant ${participant.getIdentifier()} to channel ${channelSid}`,
    );

    return this.twilioClient.chat
      .services(process.env.TWILIO_CHAT_SERVICE_ID)
      .channels(channelSid)
      .invites.create({ identity: participant.getIdentifier() });
  }

Is there more that I need to do to enable the participant to find/join the channel?


Solution

  • Have you tried setting a short timeout? The channel resource at twilio might need some time.