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.

This guide walks you through the essential steps to build a Matrix client with matrix-js-sdk: installing the package, creating an authenticated client, syncing with the homeserver, sending a message, and listening for incoming events.
Servers supporting MSC3916 (Matrix 1.11) require clients to include an Authorization header when downloading or thumbnailing media. See the authenticated media section below for details.
1

Install the package

Install matrix-js-sdk using your preferred package manager.
npm install matrix-js-sdk
pnpm is recommended by the matrix-js-sdk project. See the pnpm install guide if you do not have it.
2

Create a client

Import the SDK and call createClient with your homeserver URL, user ID, and access token.
import * as sdk from "matrix-js-sdk";

const myUserId = "@example:localhost";
const myAccessToken = "QGV4YW1wbGU6bG9jYWxob3N0.qPEvLuYfNBjxikiCjP";

const matrixClient = sdk.createClient({
    baseUrl: "http://localhost:8008",
    accessToken: myAccessToken,
    userId: myUserId,
});
createClient automatically provisions a MemoryStore for event storage, a MatrixScheduler for message queuing, and a crypto store. All of these can be overridden via the options object.To make unauthenticated requests (for example, listing public rooms), you can create a minimal client with only baseUrl:
import * as sdk from "matrix-js-sdk";

const client = sdk.createClient({ baseUrl: "https://matrix.org" });
client.publicRooms(function (err, data) {
    console.log("Public Rooms: %s", JSON.stringify(data));
});
3

Start syncing

Call startClient to begin the /sync loop. The initialSyncLimit option controls how many timeline events are fetched per room on the initial sync.
await matrixClient.startClient({ initialSyncLimit: 10 });
Listen for the ClientEvent.Sync event to know when the initial sync is complete and the client is ready to use:
import { ClientEvent } from "matrix-js-sdk";

matrixClient.once(ClientEvent.Sync, function (state, prevState, res) {
    if (state === "PREPARED") {
        console.log("prepared");
    } else {
        console.log(state);
        process.exit(1);
    }
});
The PREPARED state means the initial sync has completed and all room state is available locally. Do not attempt to read room data before this event fires.
4

Send a message

Use sendEvent to send an m.room.message event to a room. Replace "roomId" with the actual Matrix room ID (e.g. !abc123:localhost).
const content = {
    body: "message text",
    msgtype: "m.text",
};

matrixClient.sendEvent("roomId", "m.room.message", content, "", (err, res) => {
    console.log(err);
});
The SDK handles local echo automatically: the message will appear in the room timeline with an EventStatus.SENDING status immediately, before the server response arrives.
5

Listen for events

Subscribe to RoomEvent.Timeline to receive new messages across all rooms.
import { RoomEvent } from "matrix-js-sdk";

matrixClient.on(RoomEvent.Timeline, function (event, room, toStartOfTimeline) {
    if (toStartOfTimeline) {
        return; // don't print paginated results
    }
    if (event.getType() !== "m.room.message") {
        return; // only use messages
    }
    console.log(
        // the room name will update with m.room.name events automatically
        "(%s) %s :: %s",
        room.name,
        event.getSender(),
        event.getContent().body,
    );
});
The SDK emits events from MatrixClient, Room, RoomMember, and other objects. Some other commonly used events:
import { RoomMemberEvent, ClientEvent } from "matrix-js-sdk";

// Listen for low-level MatrixEvents
matrixClient.on(ClientEvent.Event, function (event) {
    console.log(event.getType());
});

// Listen for typing changes
matrixClient.on(RoomMemberEvent.Typing, function (event, member) {
    if (member.typing) {
        console.log(member.name + " is typing...");
    } else {
        console.log(member.name + " stopped typing.");
    }
});

Auto-joining rooms

A common pattern is to automatically accept room invitations. Listen for RoomEvent.MyMembership and call joinRoom when the membership becomes invite:
import { RoomEvent, KnownMembership } from "matrix-js-sdk";

matrixClient.on(RoomEvent.MyMembership, function (room, membership, prevMembership) {
    if (membership === KnownMembership.Invite) {
        matrixClient.joinRoom(room.roomId).then(function () {
            console.log("Auto-joined %s", room.roomId);
        });
    }
});

matrixClient.startClient();

Reading stored timeline events

By default, matrix-js-sdk uses MemoryStore to store events as they arrive. You can iterate over the current in-memory timeline for all rooms:
Object.keys(matrixClient.store.rooms).forEach((roomId) => {
    matrixClient.getRoom(roomId).timeline.forEach((t) => {
        console.log(t.event);
    });
});

Authenticated media

Servers that support MSC3916 (Matrix 1.11) require an Authorization header when fetching media. In Node.js environments you can construct an authenticated download URL as follows:
const downloadUrl = matrixClient.mxcUrlToHttp(
    /*mxcUrl=*/ "mxc://example.org/abc123",
    /*width=*/ undefined,
    /*height=*/ undefined,
    /*resizeMethod=*/ undefined,
    /*allowDirectLinks=*/ false,
    /*allowRedirects=*/ true,  // implied supported with authentication
    /*useAuthentication=*/ true,
);

const img = await fetch(downloadUrl, {
    headers: {
        Authorization: `Bearer ${matrixClient.getAccessToken()}`,
    },
});
// Do something with `img`.
In a future release, matrix-js-sdk will return only authentication-required URLs, making the Authorization header mandatory. Web browsers may need to use Service Workers to append the header when using media URLs in <img /> elements.

Full example

The examples/node directory in the repository contains a fully functional terminal chat client that demonstrates room listing, joining, messaging, member lists, and scrollback. To run it, edit app.js to set your homeserver, access_token, and user_id, then:
cd examples/node
npm install
node app