Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/matrix-org/matrix-js-sdk/llms.txt

Use this file to discover all available pages before exploring further.

Overview

MatrixClient is the main class in matrix-js-sdk. It wraps the Matrix Client-Server API and provides a high-level interface for authentication, room operations, messaging, media handling, and real-time sync. It extends TypedEventEmitter, so you can listen for events using .on(), .once(), and .off(). You should not instantiate MatrixClient directly. Use createClient() instead.
import { createClient } from "matrix-js-sdk";

const client = createClient({
  baseUrl: "https://matrix.org",
  accessToken: "syt_...",
  userId: "@alice:matrix.org",
});

Client Lifecycle

startClient(opts?)

Start syncing with the homeserver. Must be called before most other methods will return live data.
public async startClient(opts?: IStartClientOpts): Promise<void>
opts
IStartClientOpts
Configuration for the sync loop.
Promise\<void\>
Promise
Resolves once the sync loop has started.
await client.startClient({
  initialSyncLimit: 20,
  lazyLoadMembers: true,
});

stopClient()

Stop syncing and perform a clean shutdown of the client.
public stopClient(): void
This cancels any in-flight sync requests, clears interval timers, and stops the crypto backend. Safe to call multiple times.
client.stopClient();

clearStores(args?)

Delete all data from the persistent stores used by this client. The client must not be running when this is called.
public clearStores(
  args: { cryptoDatabasePrefix?: string } = {}
): Promise<void>
args.cryptoDatabasePrefix
string
The IndexedDB database name prefix to clear. Defaults to 'matrix-js-sdk'.
Promise\<void\>
Promise
Resolves when all stores have been cleared.
client.stopClient();
await client.clearStores();

Room Operations

createRoom(options)

Create a new Matrix room.
public async createRoom(options: ICreateRoomOpts): Promise<{ room_id: string }>
options
ICreateRoomOpts
required
Room creation options passed directly to the /createRoom API. Common fields include name, topic, visibility ("public" | "private"), preset, and invite.
room_id
string
The ID of the newly created room.
const { room_id } = await client.createRoom({
  name: "My Room",
  topic: "A test room",
  visibility: "private",
  preset: "private_chat",
});

joinRoom(roomIdOrAlias, opts?)

Join a room by its ID or alias. No-ops if already joined.
public async joinRoom(
  roomIdOrAlias: string,
  opts: IJoinRoomOpts = {}
): Promise<Room>
roomIdOrAlias
string
required
The room ID (!abc:example.com) or alias (#general:example.com) to join.
opts
IJoinRoomOpts
Optional join parameters, such as viaServers (array of server names to route the request through).
Room
Room
The Room object for the joined room.
const room = await client.joinRoom("#general:matrix.org", {
  viaServers: ["matrix.org"],
});

leave(roomId)

Leave a room.
public leave(roomId: string): Promise<EmptyObject>
roomId
string
required
The ID of the room to leave.
Promise\<EmptyObject\>
Promise
Resolves to an empty object on success.
await client.leave("!abc123:matrix.org");

getRoom(roomId)

Retrieve a room from the local store.
public getRoom(roomId: string | undefined): Room | null
roomId
string
required
The ID of the room to retrieve.
Room | null
Room | null
The Room object if found, or null if not in the store.
const room = client.getRoom("!abc123:matrix.org");
if (room) {
  console.log(room.name);
}

getRooms()

Retrieve all rooms from the local store.
public getRooms(): Room[]
Room[]
Room[]
All rooms currently in the store, or an empty array if there is no store.
const rooms = client.getRooms();
rooms.forEach((room) => console.log(room.roomId, room.name));

publicRooms(options?)

Query the homeserver’s public room directory.
public publicRooms(
  options: IRoomDirectoryOptions = {}
): Promise<IPublicRoomsResponse>
options
IRoomDirectoryOptions
Filtering options. Includes server, limit, since, and filter fields like generic_search_term.
IPublicRoomsResponse
object
Contains chunk (array of public room summaries), next_batch, and prev_batch.
const { chunk } = await client.publicRooms({ limit: 20 });
chunk.forEach((room) => console.log(room.room_id, room.name));

Messaging

sendEvent(roomId, eventType, content, txnId?)

Send a Matrix timeline event to a room.
public sendEvent<K extends keyof TimelineEvents>(
  roomId: string,
  eventType: K,
  content: TimelineEvents[K],
  txnId?: string,
): Promise<ISendEventResponse>

// Thread-scoped variant:
public sendEvent<K extends keyof TimelineEvents>(
  roomId: string,
  threadId: string | null,
  eventType: K,
  content: TimelineEvents[K],
  txnId?: string,
): Promise<ISendEventResponse>
roomId
string
required
The ID of the room to send the event to.
threadId
string | null
The event ID of the thread root. Pass null for the main timeline.
eventType
string
required
The Matrix event type, e.g. "m.room.message".
content
IContent
required
The event content object.
txnId
string
Optional transaction ID to deduplicate repeated attempts.
event_id
string
The ID assigned to the sent event by the homeserver.
const { event_id } = await client.sendEvent(
  "!abc123:matrix.org",
  "m.room.message",
  { msgtype: "m.text", body: "Hello!" },
);

sendMessage(roomId, content, txnId?)

Send an m.room.message event.
public sendMessage(
  roomId: string,
  content: RoomMessageEventContent,
  txnId?: string,
): Promise<ISendEventResponse>

// Thread-scoped variant:
public sendMessage(
  roomId: string,
  threadId: string | null,
  content: RoomMessageEventContent,
  txnId?: string,
): Promise<ISendEventResponse>
await client.sendMessage("!abc123:matrix.org", {
  msgtype: "m.text",
  body: "Hello from the SDK!",
});

sendTextMessage(roomId, body, txnId?)

Convenience wrapper around sendMessage for plain-text messages.
public sendTextMessage(
  roomId: string,
  body: string,
  txnId?: string,
): Promise<ISendEventResponse>

// Thread-scoped variant:
public sendTextMessage(
  roomId: string,
  threadId: string | null,
  body: string,
  txnId?: string,
): Promise<ISendEventResponse>
roomId
string
required
The room to send the message to.
body
string
required
The plain-text message body.
txnId
string
Optional transaction ID.
await client.sendTextMessage("!abc123:matrix.org", "Hello, Matrix!");

redactEvent(roomId, eventId, txnId?, opts?)

Redact (soft-delete) an event in a room.
public redactEvent(
  roomId: string,
  eventId: string,
  txnId?: string,
  opts?: IRedactOpts,
): Promise<ISendEventResponse>

// Thread-scoped variant:
public redactEvent(
  roomId: string,
  threadId: string | null,
  eventId: string,
  txnId?: string,
  opts?: IRedactOpts,
): Promise<ISendEventResponse>
roomId
string
required
The ID of the room containing the event.
eventId
string
required
The ID of the event to redact.
opts.reason
string
A human-readable reason for the redaction.
await client.redactEvent("!abc123:matrix.org", "$eventId", undefined, {
  reason: "Spam",
});

Membership

invite(roomId, userId, opts?)

Invite a user to a room.
public async invite(
  roomId: string,
  userId: string,
  opts: InviteOpts | string = {}
): Promise<EmptyObject>
roomId
string
required
The room to invite the user to.
userId
string
required
The MXID of the user to invite.
opts
InviteOpts | string
Options, or a plain string treated as a reason. opts.shareEncryptedHistory will share room key history if the room’s visibility allows it.
await client.invite("!abc123:matrix.org", "@bob:matrix.org");

kick(roomId, userId, reason?)

Kick a user from a room.
public kick(
  roomId: string,
  userId: string,
  reason?: string,
): Promise<EmptyObject>
await client.kick("!abc123:matrix.org", "@bob:matrix.org", "Disruptive behaviour");

ban(roomId, userId, reason?)

Ban a user from a room.
public ban(
  roomId: string,
  userId: string,
  reason?: string,
): Promise<EmptyObject>
await client.ban("!abc123:matrix.org", "@bob:matrix.org");

unban(roomId, userId)

Lift a ban from a user in a room.
public unban(roomId: string, userId: string): Promise<EmptyObject>
await client.unban("!abc123:matrix.org", "@bob:matrix.org");

User Profile

setDisplayName(name)

Set the display name of the logged-in user.
public async setDisplayName(name: string): Promise<EmptyObject>
await client.setDisplayName("Alice");

setAvatarUrl(url)

Set the avatar URL of the logged-in user.
public async setAvatarUrl(url: string): Promise<EmptyObject>
url
string
required
An MXC URL pointing to the avatar image (obtained via uploadContent).
const { content_uri } = await client.uploadContent(file);
await client.setAvatarUrl(content_uri);

getProfileInfo(userId, info?)

Fetch profile information for any user.
public getProfileInfo(
  userId: string,
  info?: string,
): Promise<{ avatar_url?: string; displayname?: string }>
userId
string
required
The MXID of the user whose profile to fetch.
info
string
Retrieve a specific field only: "displayname" or "avatar_url".
const profile = await client.getProfileInfo("@alice:matrix.org");
console.log(profile.displayname, profile.avatar_url);

Presence

setPresence(opts)

Set the presence status of the logged-in user via the Presence API.
public async setPresence(opts: IPresenceOpts): Promise<void>
opts.presence
string
required
One of "online", "offline", or "unavailable".
opts.status_msg
string
A human-readable status message.
await client.setPresence({ presence: "online", status_msg: "Available" });

Account Data

setAccountData(eventType, content)

Set user-scoped account data and wait for the echo to be received over /sync.
public async setAccountData<K extends keyof WritableAccountDataEvents>(
  eventType: K,
  content: AccountDataEvents[K] | Record<string, never>,
): Promise<EmptyObject>
eventType
string
required
The account data event type, e.g. "m.direct".
content
object
required
The content to store.
await client.setAccountData("m.direct", {
  "@bob:matrix.org": ["!abc123:matrix.org"],
});

getAccountData(eventType)

Read a user-scoped account data event from the local store.
public getAccountData<K extends keyof AccountDataEvents>(
  eventType: K,
): MatrixEvent | undefined
const event = client.getAccountData("m.direct");
const dmMap = event?.getContent();

Media

uploadContent(file, opts?)

Upload a file to the homeserver’s media repository.
public uploadContent(
  file: FileType,
  opts?: UploadOpts,
): Promise<UploadResponse>
file
FileType
required
In browsers, a File or Blob. In Node.js, a Buffer, string, or ReadStream.
opts
UploadOpts
Upload options. Includes name (filename), type (MIME type), progressHandler, and includeFilename.
content_uri
string
The MXC URI of the uploaded content, e.g. mxc://matrix.org/abc123.
const { content_uri } = await client.uploadContent(fileBlob, {
  name: "photo.jpg",
  type: "image/jpeg",
});

mxcUrlToHttp(mxcUrl, width?, height?, resizeMethod?, ...)

Convert an MXC URI to an HTTP URL.
public mxcUrlToHttp(
  mxcUrl: string,
  width?: number,
  height?: number,
  resizeMethod?: string,
  allowDirectLinks?: boolean,
  allowRedirects?: boolean,
  useAuthentication?: boolean,
): string | null
mxcUrl
string
required
The mxc:// URI to convert.
width
number
Desired thumbnail width in pixels.
height
number
Desired thumbnail height in pixels.
resizeMethod
string
Thumbnail resize method: "crop" or "scale".
If true, return non-MXC URLs as-is. This may leak information. Default: false.
allowRedirects
boolean
If true, the caller accepts 307/308 redirects. Default: false.
useAuthentication
boolean
If true, return an authenticated media URL. Implies allowRedirects. Default: false.
string | null
string | null
The HTTP URL, or null if the MXC URL is invalid.
const url = client.mxcUrlToHttp(
  "mxc://matrix.org/abc123",
  96,   // width
  96,   // height
  "crop",
);

Authentication

login(loginType, data)

Post a login request. Updates the client with returned credentials.
public login(
  loginType: LoginRequest["type"],
  data: Omit<LoginRequest, "type">,
): Promise<LoginResponse>
This method is deprecated. It mutates the MatrixClient instance inconsistently. Prefer calling loginRequest() and constructing a new MatrixClient with the returned credentials. See matrix-org/matrix-js-sdk#4502.
loginType
string
required
The login flow type, e.g. "m.login.password" or "m.login.token".
data
object
required
Flow-specific credentials, e.g. { user, password } for m.login.password.

logout(stopClient?)

Post a logout request to the homeserver, invalidating the current access token.
public async logout(stopClient?: boolean): Promise<EmptyObject>
stopClient
boolean
If true, also call stopClient() and abort all pending HTTP requests before logging out. Default: false.
await client.logout(true);

getAccessToken()

Return the current access token.
public getAccessToken(): string | null

getUserId()

Return the MXID of the logged-in user.
public getUserId(): string | null

getDeviceId()

Return the device ID of this client.
public getDeviceId(): string | null

Server Info

getVersions()

Query the server’s supported spec versions. Results are cached.
public async getVersions(): Promise<IServerVersions>
versions
string[]
Array of supported Matrix spec versions, e.g. ["v1.6", "v1.7"].
unstable_features
Record<string, boolean>
Map of unstable feature flags.

getCapabilities()

Query the homeserver’s capabilities (e.g. supported room versions, password change support).
public async getCapabilities(): Promise<Capabilities>
Capabilities
object
An object describing server capabilities. See Capabilities in serverCapabilities.ts.
const caps = await client.getCapabilities();
console.log(caps["m.room_versions"]);