Skip to main content

Send and list messages with XMTP

The message payload can be a plain string, but you can configure custom content types. To learn more, see Content types.

Send messages

To send a message, the recipient must have already started their client at least once and consequently advertised their key bundle on the network.

Messages are limited to just short of 1MB (1048214 bytes) . Use remote attachments to support larger messages.

const conversation = await xmtp.conversations.newConversation(
"0x3F11b27F323b62B159D2642964fa27C46C841897",
);
await conversation.send("Hello world");

You might want to consider optimistically sending messages. This way, the app will not have to wait for the network to process the message first. Optimistic sending is especially useful for mobile apps where the user might have a spotty connection, making the app continue to run with multiple threads.

// standard (string) message
const preparedTextMessage = await conversation.prepareMessage(messageText);
//After preparing an optimistic message, use its `send` method to send it.
try {
preparedMessage.send();
} catch (e) {
// handle error, enable canceling and retries (see below)
}

List messages in a conversation

You can receive the complete message history in a conversation.

for (const conversation of await xmtp.conversations.list()) {
// All parameters are optional and can be omitted
const opts = {
// Only show messages from last 24 hours
startTime: new Date(new Date().setDate(new Date().getDate() - 1)),
endTime: new Date(),
};
const messagesInConversation = await conversation.messages(opts);
}

List messages in a conversation with pagination

If a conversation has a lot of messages, it's more performant to retrieve and process the messages page by page instead of handling all of the messages at once.

Automatically handled by the SDK

Note on Group Chats

The methods for sending and listing messages, as well as handling unsupported content types, are applicable to both one-on-one and group conversations within XMTP. This means you can use the same approach to manage messages in group chats as you would in individual conversations.

For additional information on group chat-specific features, such as managing group members or listening for new messages in a group chat, please see the Group Chats documentation.

Handle an unsupported content type error

As more custom and standards-track content types enter the XMTP ecosystem, your app might receive a content type your app doesn't support. This could crash your app.

To avoid crashing your app, code your app to detect, log, and handle the error. For example:

const codec = xmtp.codecFor(content.contentType);
if (!codec) {
const fallback = `missing codec for content type "${content.contentType.toString()}"`;
throw new Error(fallback);
}

Was the information on this page helpful?
powered by XMTP