Support read receipts in your app built with XMTP
Use the read receipt content type to support read receipts in your app. A read receipt is a timestamp
that indicates when a message was read. It is sent as a message and can be used to calculate the time since the last message was read.
Provide an opt-out option
While this is a per-app decision, the best practice is to provide users with the option to opt out of sending read receipts. If a user opts out, when they read a message, a read receipt will not be sent to the sender of the message.
Configure the content type
npm i @xmtp/content-type-read-receipt
import {
ContentTypeReadReceipt,
ReadReceiptCodec,
} from "@xmtp/content-type-read-receipt";
// Create the XMTP client
const xmtp = await Client.create(signer, { env: "dev" });
xmtp.registerCodec(new ReadReceiptCodec());
Send a read receipt
// The content of a read receipt message must be an empty object.
await conversation.messages.send({}, ContentTypeReadReceipt);
Receive a read receipt
Here's how you can receive a read receipt:
if (message.contentType.sameAs(ContentTypeReadReceipt)) {
// The message is a read receipt
const timestamp = message.sent;
}
Display a read receipt
ReadReceipts
have an undefined
or nil
fallback, indicating the message is not expected to be displayed. To learn more, see Handle unsupported content types section.
Notifications and read receipts
Read receipts have shouldPush
set to false
, which means that read receipts do not trigger push notifications as long as the notification server respects this flag.
Use a read receipt
Generally, a read receipt indicator should be displayed under the message it's associated with. The indicator can include a timestamp. Ultimately, how you choose to display a read receipt indicator is completely up to you.
The read receipt is provided as an empty message whose timestamp provides the data needed for the indicators. Be sure to filter out read receipt empty messages and not display them to users.
You can use a read receipt timestamp to calculate the time since the last message was read. While iterating through messages, you can be sure that the last message was read at the timestamp of the read receipt if the string of the timestamp is lower.