• Stars
    star
    1,505
  • Rank 31,161 (Top 0.7 %)
  • Language
    TypeScript
  • License
    Apache License 2.0
  • Created over 9 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Matrix Client-Server SDK for JavaScript

npm Tests Static Analysis Quality Gate Status Coverage Vulnerabilities Bugs

Matrix JavaScript SDK

This is the Matrix Client-Server SDK for JavaScript and TypeScript. This SDK can be run in a browser or in Node.js.

The Matrix specification is constantly evolving - while this SDK aims for maximum backwards compatibility, it only guarantees that a feature will be supported for at least 4 spec releases. For example, if a feature the js-sdk supports is removed in v1.4 then the feature is eligible for removal from the SDK when v1.8 is released. This SDK has no guarantee on implementing all features of any particular spec release, currently. This can mean that the SDK will call endpoints from before Matrix 1.1, for example.

Quickstart

In a browser

Note, the browserify build has been deprecated. Please use a bundler like webpack or vite instead.

Download the browser version from https://github.com/matrix-org/matrix-js-sdk/releases/latest and add that as a <script> to your page. There will be a global variable matrixcs attached to window through which you can access the SDK. See below for how to include libolm to enable end-to-end-encryption.

The browser bundle supports recent versions of browsers. Typically this is ES2015 or > 0.5%, last 2 versions, Firefox ESR, not dead if using browserlists.

Please check the working browser example for more information.

In Node.js

Ensure you have the latest LTS version of Node.js installed. This library relies on fetch which is available in Node from v18.0.0 - it should work fine also with polyfills. If you wish to use a ponyfill or adapter of some sort then pass it as fetchFn to the MatrixClient constructor options.

Using yarn instead of npm is recommended. Please see the Yarn install guide if you do not have it already.

yarn add matrix-js-sdk

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));
});

See below for how to include libolm to enable end-to-end-encryption. Please check the Node.js terminal app for a more complex example.

You can also use the sdk with Deno (import npm:matrix-js-sdk) but its not officialy supported.

To start the client:

await client.startClient({ initialSyncLimit: 10 });

You can perform a call to /sync to get the current state of the client:

client.once("sync", function (state, prevState, res) {
    if (state === "PREPARED") {
        console.log("prepared");
    } else {
        console.log(state);
        process.exit(1);
    }
});

To send a message:

const content = {
    body: "message text",
    msgtype: "m.text",
};
client.sendEvent("roomId", "m.room.message", content, "", (err, res) => {
    console.log(err);
});

To listen for message events:

client.on("Room.timeline", function (event, room, toStartOfTimeline) {
    if (event.getType() !== "m.room.message") {
        return; // only use messages
    }
    console.log(event.event.content.body);
});

By default, the matrix-js-sdk client uses the MemoryStore to store events as they are received. For example to iterate through the currently stored timeline for a room:

Object.keys(client.store.rooms).forEach((roomId) => {
    client.getRoom(roomId).timeline.forEach((t) => {
        console.log(t.event);
    });
});

What does this SDK do?

This SDK provides a full object model around the Matrix Client-Server API and emits events for incoming data and state changes. Aside from wrapping the HTTP API, it:

  • Handles syncing (via /initialSync and /events)
  • Handles the generation of "friendly" room and member names.
  • Handles historical RoomMember information (e.g. display names).
  • Manages room member state across multiple events (e.g. it handles typing, power levels and membership changes).
  • Exposes high-level objects like Rooms, RoomState, RoomMembers and Users which can be listened to for things like name changes, new messages, membership changes, presence changes, and more.
  • Handle "local echo" of messages sent using the SDK. This means that messages that have just been sent will appear in the timeline as 'sending', until it completes. This is beneficial because it prevents there being a gap between hitting the send button and having the "remote echo" arrive.
  • Mark messages which failed to send as not sent.
  • Automatically retry requests to send messages due to network errors.
  • Automatically retry requests to send messages due to rate limiting errors.
  • Handle queueing of messages.
  • Handles pagination.
  • Handle assigning push actions for events.
  • Handles room initial sync on accepting invites.
  • Handles WebRTC calling.

Later versions of the SDK will:

  • Expose a RoomSummary which would be suitable for a recents page.
  • Provide different pluggable storage layers (e.g. local storage, database-backed)

Usage

Conventions

Emitted events

The SDK will emit events using an EventEmitter. It also emits object models (e.g. Rooms, RoomMembers) when they are updated.

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

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

// start the client to setup the connection to the server
client.startClient();

Promises and Callbacks

Most of the methods in the SDK are asynchronous: they do not directly return a result, but instead return a Promise which will be fulfilled in the future.

The typical usage is something like:

  matrixClient.someMethod(arg1, arg2).then(function(result) {
    ...
  });

Alternatively, if you have a Node.js-style callback(err, result) function, you can pass the result of the promise into it with something like:

matrixClient.someMethod(arg1, arg2).nodeify(callback);

The main thing to note is that it is problematic to discard the result of a promise-returning function, as that will cause exceptions to go unobserved.

Methods which return a promise show this in their documentation.

Many methods in the SDK support both Node.js-style callbacks and Promises, via an optional callback argument. The callback support is now deprecated: new methods do not include a callback argument, and in the future it may be removed from existing methods.

Examples

This section provides some useful code snippets which demonstrate the core functionality of the SDK. These examples assume the SDK is setup like this:

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,
});

Automatically join rooms when invited

matrixClient.on("RoomMember.membership", function (event, member) {
    if (member.membership === "invite" && member.userId === myUserId) {
        matrixClient.joinRoom(member.roomId).then(function () {
            console.log("Auto-joined %s", member.roomId);
        });
    }
});

matrixClient.startClient();

Print out messages for all rooms

matrixClient.on("Room.timeline", function (event, room, toStartOfTimeline) {
    if (toStartOfTimeline) {
        return; // don't print paginated results
    }
    if (event.getType() !== "m.room.message") {
        return; // only print messages
    }
    console.log(
        // the room name will update with m.room.name events automatically
        "(%s) %s :: %s",
        room.name,
        event.getSender(),
        event.getContent().body,
    );
});

matrixClient.startClient();

Output:

  (My Room) @megan:localhost :: Hello world
  (My Room) @megan:localhost :: how are you?
  (My Room) @example:localhost :: I am good
  (My Room) @example:localhost :: change the room name
  (My New Room) @megan:localhost :: done

Print out membership lists whenever they are changed

matrixClient.on("RoomState.members", function (event, state, member) {
    const room = matrixClient.getRoom(state.roomId);
    if (!room) {
        return;
    }
    const memberList = state.getMembers();
    console.log(room.name);
    console.log(Array(room.name.length + 1).join("=")); // underline
    for (var i = 0; i < memberList.length; i++) {
        console.log("(%s) %s", memberList[i].membership, memberList[i].name);
    }
});

matrixClient.startClient();

Output:

  My Room
  =======
  (join) @example:localhost
  (leave) @alice:localhost
  (join) Bob
  (invite) @charlie:localhost

API Reference

A hosted reference can be found at http://matrix-org.github.io/matrix-js-sdk/index.html

This SDK uses Typedoc doc comments. You can manually build and host the API reference from the source files like this:

  $ yarn gendoc
  $ cd _docs
  $ python -m http.server 8005

Then visit http://localhost:8005 to see the API docs.

End-to-end encryption support

The SDK supports end-to-end encryption via the Olm and Megolm protocols, using libolm. It is left up to the application to make libolm available, via the Olm global.

It is also necessary to call await matrixClient.initCrypto() after creating a new MatrixClient (but before calling matrixClient.startClient()) to initialise the crypto layer.

If the Olm global is not available, the SDK will show a warning, as shown below; initCrypto() will also fail.

Unable to load crypto module: crypto will be disabled: Error: global.Olm is not defined

If the crypto layer is not (successfully) initialised, the SDK will continue to work for unencrypted rooms, but it will not support the E2E parts of the Matrix specification.

To provide the Olm library in a browser application:

To provide the Olm library in a node.js application:

  • yarn add https://packages.matrix.org/npm/olm/olm-3.1.4.tgz (replace the URL with the latest version you want to use from https://packages.matrix.org/npm/olm/)
  • global.Olm = require('olm'); before loading matrix-js-sdk.

If you want to package Olm as dependency for your node.js application, you can use yarn add https://packages.matrix.org/npm/olm/olm-3.1.4.tgz. If your application also works without e2e crypto enabled, add --optional to mark it as an optional dependency.

Contributing

This section is for people who want to modify the SDK. If you just want to use this SDK, skip this section.

First, you need to pull in the right build tools:

 $ yarn install

Building

To build a browser version from scratch when developing::

 $ yarn build

To run tests (Jest):

 $ yarn test

Note The sync-browserify.spec.ts requires a browser build (yarn build) in order to pass

To run linting:

 $ yarn lint

More Repositories

1

synapse

Synapse: Matrix homeserver written in Python/Twisted.
Python
11,791
star
2

dendrite

Dendrite is a second-generation Matrix homeserver written in Go!
Go
4,696
star
3

matrix-rust-sdk

Matrix Client-Server SDK for Rust
Rust
1,151
star
4

matrix-react-sdk

Matrix SDK for React Javascript
TypeScript
1,095
star
5

matrix-spec-proposals

Proposals for changes to the matrix specification
889
star
6

matrix-appservice-discord

A bridge between Matrix and Discord.
TypeScript
803
star
7

matrix.to

A simple stateless privacy-protecting URL redirecting service for Matrix
JavaScript
766
star
8

thirdroom

Open, decentralised, immersive worlds built on Matrix
C
599
star
9

matrix-appservice-irc

Node.js IRC bridge for Matrix
TypeScript
457
star
10

matrix-ios-sdk

The Matrix SDK for iOS
Objective-C
433
star
11

pinecone

Peer-to-peer overlay routing for the Matrix ecosystem
Go
428
star
12

matrix.org

matrix.org public website
JavaScript
413
star
13

matrix-android-sdk

The Matrix SDK for Android - DEPRECATED
Java
376
star
14

mjolnir

A moderation tool for Matrix
TypeScript
325
star
15

go-neb

Extensible matrix bot written in Go
Go
281
star
16

pantalaimon

E2EE aware proxy daemon for matrix clients.
Python
279
star
17

matrix-appservice-slack

A Matrix <--> Slack bridge
TypeScript
271
star
18

gomatrix

A Golang Matrix client
Go
269
star
19

sydent

Sydent: Reference Matrix Identity Server
Python
259
star
20

matrix-python-sdk

Matrix Client-Server SDK for Python 2 and 3
Python
256
star
21

sliding-sync

Proxy implementation of MSC3575's sync protocol.
Go
250
star
22

purple-matrix

Libpurple protocol plugin for matrix
C
224
star
23

matrix-ircd

An IRCd implementation backed by Matrix.
Rust
224
star
24

matrix-android-sdk2

Matrix SDK for Android, extracted from the Element Android application
Kotlin
189
star
25

matrix-spec

The Matrix protocol specification
HTML
188
star
26

matrix-hookshot

A bridge between Matrix and multiple project management services, such as GitHub, GitLab and JIRA.
TypeScript
185
star
27

vodozemac

An implementation of Olm and Megolm in pure Rust.
Rust
171
star
28

matrix-bifrost

General purpose bridging with a variety of backends including libpurple and xmpp.js
TypeScript
162
star
29

rust-synapse-compress-state

A tool to compress some state in a Synapse instance's database
Rust
147
star
30

matrix-appservice-bridge

Bridging infrastructure for Application Services
TypeScript
141
star
31

matrix-ios-kit

Reusable UI interfaces to ease building of Matrix client apps
Objective-C
128
star
32

sygnal

Sygnal: reference Push Gateway for Matrix
Python
128
star
33

matrix-authentication-service

OAuth2.0 + OpenID Provider for Matrix Homeservers
Rust
111
star
34

matrix-synapse-ldap3

An LDAP3 auth provider for Synapse
Python
107
star
35

cerulean

An experimental Matrix client for playing with freestyle public threaded conversations
JavaScript
103
star
36

waterfall

A cascading stream forwarding unit for scalable, distributed voice and video conferencing over Matrix
Go
98
star
37

synapse-s3-storage-provider

Synapse storage provider to fetch and store media in Amazon S3
Python
92
star
38

matrix-rich-text-editor

Matrix Rich Text Editor
Rust
92
star
39

meshsim

Matrix mesh simulator
Python
90
star
40

matrix-static

A static golang generated preview of public world readable Matrix rooms.
Go
87
star
41

seshat

A Matrix message database/indexer
Rust
86
star
42

matrix-viewer

View the history of public and world readable Matrix rooms
JavaScript
74
star
43

matrix-appservice-node

Matrix Application Service framework in Node.js
TypeScript
71
star
44

sytest

Black-box integration testing for Matrix homeservers
Perl
66
star
45

matrix-federation-tester

Tester for matrix federation written in golang.
Go
61
star
46

complement

Matrix compliance test suite
Go
61
star
47

docker-jitsi

Docker files for building images and running jitsi-meet in Docker containers
Lua
58
star
48

matrix-widget-api

JavaScript/TypeScript API for widgets & web clients to communicate
TypeScript
57
star
49

gomatrixserverlib

Go library for matrix federation.
Go
56
star
50

olm

An implementation of the Double Ratchet cryptographic ratchet in C++/C
54
star
51

Matrix-NEB

N E Bot: Generic bot for Matrix with plugin support
Python
49
star
52

rust-opa-wasm

Open Policy Agent WebAssembly Rust SDK
Rust
46
star
53

naffka

Single in-process implementation of the sarama golang kafka APIs
Go
45
star
54

matrix-ios-console

The sample Matrix client for iOS
Objective-C
45
star
55

conference-bot

The conductor for your orchestra^Wconference
TypeScript
44
star
56

gsoc

JavaScript
43
star
57

matrix-appservice-gitter

Matrix <-> Gitter bridge
JavaScript
40
star
58

coap-proxy

HTTP<->CoAP proxy
Go
39
star
59

matrix-appservice-tg

Matrix<->Telegram user-puppeting portal
JavaScript
37
star
60

dendron

Dendron was an experimental Matrix homeserver, succeeded by Dendrite.
Go
35
star
61

matrix-vr-demo

Matrix.org Virtual Reality Demo
JavaScript
31
star
62

python-canonicaljson

Canonical JSON
Python
31
star
63

bullettime

An experimental golang Matrix homeserver
Go
31
star
64

matrix-angular-sdk

JavaScript
28
star
65

matrix-rust-components-swift

Swift package providing components from the matrix-rust-sdk
Swift
27
star
66

rageshake

Bug report server
Go
27
star
67

matrix-android-console

Java
26
star
68

matrix-android-sdk2-sample

Example project for using the android sdk
Kotlin
26
star
69

fed-tester-ui

UI for the matrix federation tester (forked from https://git.lain.haus/f0x/fed-tester)
JavaScript
26
star
70

lb

MSC3079 Low Bandwidth library for servers and clients
Go
25
star
71

prosody-mod-auth-matrix-user-verification

Matrix user verification auth for Prosody
Lua
24
star
72

voip-tester

Tests VoIP
JavaScript
23
star
73

thirdroom-unity-exporter

C#
23
star
74

matrix-user-verification-service

Service to verify details of a user based on a Open ID token.
JavaScript
23
star
75

matrix-search

A generic search engine daemon
Go
22
star
76

tardis

Time Agnostic Room DAG Inspection Service
JavaScript
21
star
77

synapse-auto-accept-invite

Synapse module to automatically accept invites
Python
18
star
78

libp2p-proxy

A p2p transport shim for p2p matrix.
Go
18
star
79

patience

Full stack integration testing for Matrix clients and servers
TypeScript
18
star
80

matrix-sentry-webhooks

Sentry webhooks integration bot for Matrix.
JavaScript
17
star
81

matrix-appservice-verto

A Matrix <--> Verto bridge, designed for conferencing
JavaScript
16
star
82

go-sqlite3-js

Go SQL driver for sqlite3 in browser (sql.js) from go-wasm
Go
15
star
83

matrix-appservice-rocketchat

JavaScript
15
star
84

matrix-content-scanner

[DEPRECATED] A web service for scanning media hosted by a Matrix media repository. Replaced by https://github.com/vector-im/matrix-content-scanner-python
JavaScript
13
star
85

synapse-user-restrictions

This module allows restricting users from performing actions such as creating rooms or sending invites.
Python
13
star
86

docker-dehydrated

A docker image we use internally for managing certificates.
Shell
13
star
87

matrix-rust-components-kotlin

Kotlin
12
star
88

matrix-rust-sdk-crypto-wasm

Rust
12
star
89

matrix-websockets-proxy

Websockets wrapper for matrix.org homeservers
Go
12
star
90

panopticon

panopticon records usage metrics from homeservers
Go
11
star
91

matrix-files-sdk

JS/TS SDK for working with files and folders in Matrix
TypeScript
11
star
92

remember-this-rs

A simple Rust crate to cache data both in-memory and on disk
Rust
11
star
93

complement-crypto

Go
10
star
94

allchange

A multi-project changelog generator
TypeScript
10
star
95

python-unpaddedbase64

Unpadded Base64
Python
10
star
96

synapse-email-account-validity

Account validity plugin for Synapse using email
Python
10
star
97

matrixmon

A small end-to-end prober and Prometheus stats exporter for a Matrix homeserver
Perl
10
star
98

matrix-synapse-saml-mozilla

Mozilla flavour of a Synapse SAML mapping provider
Python
9
star
99

vodozemac-bindings

Language bindings for vodozemac
Rust
9
star
100

synapse-config-generator

A web based synapse config generator
JavaScript
9
star