Skip to main content

Build custom content types for use with XMTP

caution

Your custom content type WILL NOT automatically be supported by other apps and will display fallback text in them instead.

Building a custom content type enables you to manage data in a way that is more personalized or specialized to the needs of your app.

For more common content types, you can usually find a standard or standards-track content type to serve your needs.

If your custom content type generates interest within the developer community, consider proposing it as a standard content type through the XIP process.

Create the content type

Create the custom content type by creating a new file

import { ContentTypeId } from "@xmtp/xmtp-js";

// Create a unique identifier for your content type
const ContentTypeMultiplyNumbers = new ContentTypeId({
authorityId: "your.domain",
typeId: "multiply-number",
versionMajor: 1,
versionMinor: 0,
});

// Define the MultiplyCodec class
class ContentTypeMultiplyNumberCodec {
get contentType() {
return ContentTypeMultiplyNumbers;
}

// The encode method accepts an object with two numbers (a, b) and encodes it as a byte array
encode({ a, b }) {
return {
type: ContentTypeMultiplyNumbers,
parameters: {},
content: new TextEncoder().encode(JSON.stringify({ a, b })),
};
}

// The decode method decodes the byte array, parses the string into numbers (a, b), and returns their product
decode(content: { content: any }) {
const uint8Array = content.content;
const { a, b } = JSON.parse(new TextDecoder().decode(uint8Array));
return a * b;
}

fallback(content: string): string | undefined {
return `Can’t display "${content}". This app doesn’t support "${content}".`;
//return undefined; if you don't want the content type to be displayed.
}
}

Configure the content types

Import and register the custom content type.

import { ContentTypeMultiplyNumberCodec } from "./xmtp-content-type-multiply-number";

const xmtp = await Client.create(signer, {
env: "dev",
});
xmtp.registerCodec(new ContentTypeMultiplyNumberCodec());

Send the content

Send a message using the custom content type. This code sample demonstrates how to use the MultiplyCodec custom content type to perform multiplication operations.

const numbersToMultiply = { a: 3, b: 7 };

conversation.send(numbersToMultiply, {
contentType: ContentTypeMultiplyNumbers,
});

Receive the content

To use the result of the multiplication operation, add a renderer for the custom content type.

if (message.contentType.sameAs(ContentTypeMultiplyNumber)) {
return message.content; // 21
}

Was the information on this page helpful?
powered by XMTP