Matrix JavaScript SDK

41.4.0-rc.0 · active · verified Tue Apr 21

The Matrix JavaScript SDK (`matrix-js-sdk`) is the official client-server SDK for interacting with the Matrix open standard for secure, decentralized communication. It provides a comprehensive API for building Matrix clients, bots, and integrations, supporting both browser and Node.js environments. The current stable version is 41.3.0, with frequent release candidates like 41.4.0-rc.0 incorporating the latest Matrix specification updates and features. The project is actively maintained and sponsored by Element, who leverage it in their flagship web and desktop clients. Key differentiators include its robust end-to-end encryption support, comprehensive implementation of the Matrix client-server API, and its role as the foundational library for numerous Matrix ecosystem projects.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Matrix client, start syncing, listen for global sync state changes, fetch public rooms, and process incoming messages. It also includes comments for setting up E2E and sending messages.

import * as sdk from "matrix-js-sdk";
import { ClientEvent, RoomEvent } from 'matrix-js-sdk';

const client = sdk.createClient({
    baseUrl: "https://matrix.org",
    // Store client data in local storage or a custom store
    // localStorage is often used in browsers, for Node.js consider 'matrix-js-sdk/lib/nodejs-sdk/src/node-crypto-store'
    store: new sdk.MemoryStore(), 
    // For E2E, a crypto store is essential
    cryptoStore: new sdk.MemoryCryptoStore(), 
});

client.once(ClientEvent.SYNC_STATE, async (state, prevState, res) => {
    if (state === "PREPARED") {
        console.log("Client prepared and synced.");

        // Example: Listen for new messages
        client.on(RoomEvent.Timeline, function (event, room, toStartOfTimeline) {
            if (event.getType() !== "m.room.message" || toStartOfTimeline) {
                return; // Only process new messages, not historical ones on initial sync
            }
            console.log(`[${room.name || room.roomId}] <${event.getSender()}> ${event.getContent().body}`);
        });

        // Example: Get public rooms
        client.publicRooms(function (err, data) {
            if (err) {
                console.error("Error fetching public rooms:", err);
                return;
            }
            console.log("Public Rooms:", data.chunk.map(r => r.name));
        });

        // To send a message (requires authentication and a joined room)
        // const roomId = "!yourroomid:matrix.org";
        // const content = {
        //     body: "Hello from matrix-js-sdk!",
        //     msgtype: "m.text",
        // };
        // try {
        //     await client.sendEvent(roomId, "m.room.message", content, "");
        //     console.log("Message sent!");
        // } catch (e) {
        //     console.error("Error sending message:", e);
        // }

    } else {
        console.log(`Sync state changed to: ${state}`);
    }
});

console.log("Starting client...");
client.startClient({
    initialSyncLimit: 10,
    // Set `syncFromTokens` to `false` for new clients, `true` for resuming existing sessions
    syncFromTokens: false,
}).catch(e => console.error("Failed to start client:", e));

view raw JSON →