Message replies

Reply to messages that have been previously sent in the chat room.

Message replies are implemented using the metadata field when you send a message.

Send a reply

Use the metadata field of a message to store the reply when you send a message.

You need to at least include the serial of the parent message that you're replying to. Other information can be included such as a preview of the text:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

async function sendReply(replyToMessage, replyText) {
  const metadata = {
    reply: {
      serial: replyToMessage.serial,
      timestamp: replyToMessage.createdAt.getTime(),
      clientId: replyToMessage.clientId,
      previewText: replyToMessage.text.substring(0, 140)
    }
  };

  await room.messages.send({
    text: replyText,
    metadata: metadata
  });
}

Subscribe to message replies

Message replies will be received as normal messages in the room using the subscribe() method.

You just need to handle storing and displaying the reply:

Store reply information

When a user replies to a message, extract and store the parent message details:

1

2

3

4

5

6

7

8

function prepareReply(parentMessage) {
  return {
    serial: parentMessage.serial,
    createdAt: parentMessage.createdAt.getTime(),
    clientId: parentMessage.clientId,
    previewText: parentMessage.text.substring(0, 140)
  };
}

If a parent message isn't in local state, fetch it directly using its serial:

1

2

3

4

async function fetchParentMessage(replyData) {
  const message = await room.messages.get(replyData.serial);
  return message;
}

Display replies

Check incoming messages for reply metadata and display accordingly:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

room.messages.subscribe((messageEvent) => {
  const message = messageEvent.message;

  if (message.metadata?.reply) {
    const replyData = message.metadata.reply;
    const parentMessage = localMessages.find(msg => msg.serial === replyData.serial);

    if (parentMessage) {
      console.log(`Reply to ${parentMessage.clientId}: ${parentMessage.text}`);
    } else {
      console.log(`Reply to ${replyData.clientId}: ${replyData.previewText}`);
    }
  }

  console.log(`Message: ${message.text}`);
});

Considerations

Consider the following when implementing message replies:

  • Older messages may not be available depending on message persistence settings.
  • Messages can be updated, potentially removing references to replies.
  • The metadata field is not server-validated.
  • Nested replies can be complex and expensive to implement, so consider limiting reply depth.
Select...