by dax

A full-featured Matrix protocol SDK for JavaScript and TypeScript, supporting real-time messaging, end-to-end encryption, WebRTC calling, and room management in both Node.js and browser environments.
This block provides the full Matrix Client-Server SDK for JavaScript and TypeScript, enabling real-time messaging, end-to-end encryption, room management, and WebRTC calling via the Matrix protocol. It targets Node.js backends, browser applications, and TypeScript projects that need to connect to any Matrix homeserver. The typical buyer is a developer building a chat client, bot, or integration layer on top of the Matrix ecosystem.
@types/ - TypeScript type declarations for events, crypto, push rules, auth, media, and morecommon-crypto/ - Shared cryptographic utilities used across crypto backendscrypto/ - Legacy Olm/Megolm end-to-end encryption implementationcrypto-api/ - Stable public API surface for E2E crypto (use this, not crypto/)extensible_events_v1/ - Extensible events parsing per Matrix spechttp-api/ - Fetch-based HTTP client, upload handling, error types, Matrix prefixesmatrixrtc/ - MatrixRTC session management, call membership, LiveKit transportmodels/ - Core domain models: Room, MatrixEvent, User, Device, Thread, etc.oidc/ - OIDC authentication and token managementrendezvous/ - QR-code / device rendezvous login flowrust-crypto/ - Rust/WASM crypto backend (matrix-sdk-crypto-wasm)store/ - Storage backends: MemoryStore, IndexedDButils/ - Internal utility helperswebrtc/ - Legacy WebRTC call managementclient.ts - MatrixClient: the central class for all server interactionsmatrix.ts / index.ts - Package entry point; re-exports everything publicsecret-storage.ts - Secret storage key managementsync.ts / sync-accumulator.ts - Sync loop and event accumulationsliding-sync.ts / sliding-sync-sdk.ts - MSC3575 sliding sync supportlogger.ts - Loglevel-based loggererrors.ts - MatrixError and related error typesinteractive-auth.ts - UI Auth flow handlingSpin up an isolated sandbox and run it server-side — no local setup.
Tetrees AI Review of this version
This TypeScript cli / script completed archive review with strong static results. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Pipeline avcp-2026-08-04.1 · SHA-256 8289585520d2bf24…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Reviewed Aug 4, 2026
Push this product straight into your AI IDE, web builder or cloud IDE.
Connect Tetrees to a compatible AI IDE, list products you own, and request the verified ZIP without exposing seller upload controls.
No reviews yet.
Sign in to join the discussion
Loading discussion…
timeline-window.ts - Paginated timeline window helperpushprocessor.ts - Push rule evaluationscheduler.ts - Request scheduler with retry logicfilter.ts / filter-component.ts - Room/event filter constructionevent-mapper.ts - Raw event JSON → MatrixEvent conversioncontent-helpers.ts - Helpers for constructing message contentautodiscovery.ts - .well-known server discoverynpm install user@example.com
# Peer / runtime deps pulled in transitively, but pin if you use them directly:
npm install @matrix-org/matrix-sdk-crypto-wasm another-json bs58 \
content-type jwt-decode loglevel matrix-events-sdk matrix-widget-api \
oidc-client-ts p-retry sdp-transform unhomoglyph uuid @babel/runtime
Native / build notes:
@matrix-org/matrix-sdk-crypto-wasm ships a .wasm binary. Bundlers (webpack, vite) must be configured to handle *.wasm assets (e.g. experiments: { asyncWebAssembly: true } in webpack 5).npm install.crypto/ backend or omit E2E encryption.Copy source into your project (or install via npm; the source root maps to src/ in the published package):
your-project/
└── src/
└── matrix-sdk/ ← drop source/ contents here
tsconfig.json - ensure moduleResolution supports .ts extensions or path aliases:
{
"compilerOptions": {
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"target": "ES2020",
"lib": ["ES2020", "DOM"]
}
}
Import from the index - always import from the top-level entry point:
import * as sdk from "matrix-js-sdk";
// or from local source:
import * as sdk from "./matrix-sdk/index.ts";
Environment variables - none required by default. For authenticated media (MSC3916 / Matrix 1.11), pass useAuthenticatedMedia: true in the client config.
WASM initialisation - if using the Rust crypto backend, call it before creating the client:
import { RustCrypto } from "./matrix-sdk/rust-crypto";
// The backend is initialised automatically when you call initRustCrypto()
createClientimport { createClient, type ICreateClientOpts } from "matrix-js-sdk";
function createClient(opts: ICreateClientOpts): MatrixClient;
Factory function that constructs and returns a MatrixClient. Pass at minimum { baseUrl: string }. Optionally supply userId, accessToken, and a store. This is the primary entry point for the entire SDK.
MatrixClientimport { MatrixClient } from "matrix-js-sdk";
The central class. Exposes methods for syncing (startClient), sending events (sendEvent, sendMessage), room management (joinRoom, createRoom), crypto (getCrypto, initRustCrypto), and media upload (uploadContent). Emits typed events from ClientEvent, RoomEvent, MatrixEventEvent, etc.
MatrixHttpApi / MatrixErrorimport { MatrixHttpApi, MatrixError, Method } from "matrix-js-sdk";
MatrixHttpApi wraps fetch with Matrix-specific logic including authenticated uploads and rate-limit retry. MatrixError is the standard error thrown for non-2xx Matrix responses; inspect .errcode and .data for server error details. Use these directly when building custom request layers.
CryptoApi (from crypto-api/)import type { CryptoApi } from "matrix-js-sdk/src/crypto-api";
const crypto: CryptoApi | undefined = client.getCrypto();
The stable interface for all E2E crypto operations: device verification, key backup, secret storage, and cross-signing. Always obtain it via client.getCrypto() rather than constructing it directly.
MatrixRTCSessionManager / MatrixRTCSessionimport { MatrixRTCSessionManager, MatrixRTCSession } from "matrix-js-sdk/src/matrixrtc";
Manages the lifecycle of MatrixRTC group call sessions. MatrixRTCSessionManager tracks active sessions per room; MatrixRTCSession represents a single call, including membership and key distribution.
Connect to a homeserver anonymously and retrieve public rooms, demonstrating the minimal client setup.
import * as sdk from "matrix-js-sdk";
async function listPublicRooms(): Promise<void> {
const client = sdk.createClient({ baseUrl: "https://matrix.org" });
const result = await client.publicRooms({ limit: 10 });
for (const room of result.chunk) {
console.log(room.room_id, room.name);
}
}
listPublicRooms().catch(console.error);
Full login, sync loop, and message send using a real Matrix account.
import * as sdk from "matrix-js-sdk";
import { ClientEvent, RoomEvent } from "matrix-js-sdk";
async function run(): Promise<void> {
const client = sdk.createClient({ baseUrl: "https://my.homeserver.org" });
await client.loginWithPassword("@alice:my.homeserver.org", "s3cr3t");
await new Promise<void>((resolve) => {
client.once(ClientEvent.Sync, (state) => {
if (state === "PREPARED") resolve();
});
client.startClient({ initialSyncLimit: 10 });
});
const roomId = "!someroom:my.homeserver.org";
await client.sendTextMessage(roomId, "Hello from matrix-js-sdk!");
client.on(RoomEvent.Timeline, (event, room) => {
if (event.getType() === "m.room.message") {
console.log(`[${room?.name}] ${event.getSender()}: ${event.getContent().body}`);
}
});
}
run().catch(console.error);
Initialise the Rust crypto backend, bootstrap cross-signing, and request a verification.
import * as sdk from "matrix-js-sdk";
import type { CryptoApi, VerificationRequest } from "matrix-js-sdk/src/crypto-api";
async function setupCrypto(): Promise<void> {
const client = sdk.createClient({
baseUrl: "https://my.homeserver.org",
userId: "@alice:my.homeserver.org",
accessToken: "syt_...",
deviceId: "MYDEVICE",
});
await client.initRustCrypto();
await client.startClient({ initialSyncLimit: 0 });
const crypto: CryptoApi | undefined = client.getCrypto();
if (!crypto) throw new Error("Crypto not initialised");
const ownDevices = await crypto.getUserDeviceInfo(["@alice:my.homeserver.org"]);
console.log("Own devices:", ownDevices);
// Request verification with another device
const request: VerificationRequest = await crypto.requestOwnUserVerification();
console.log("Verification request ID:", request.transactionId);
}
setupCrypto().catch(console.error);
import * as sdk from "matrix-js-sdk";
import { readFileSync } from "fs";
async function uploadFile(): Promise<void> {
const client = sdk.createClient({
baseUrl: "https://my.homeserver.org",
accessToken: "syt_...",
useAuthenticatedMedia: true,
});
const fileBuffer = readFileSync("./photo.jpg");
const response = await client.uploadContent(fileBuffer, {
type: "image/jpeg",
name: "photo.jpg",
});
console.log("MXC URI:", response.content_uri);
}
uploadFile().catch(console.error);
index.ts / matrix.ts - Single entry point; re-exports every public symbol. Always import from here.client.ts - MatrixClient class: 10 000+ lines covering the entire client-server API.crypto-api/ - Stable, versioned interface for E2E crypto; prefer over importing from crypto/ directly.crypto/ - Legacy Libolm-based crypto implementation, kept for compatibility.rust-crypto/ - Rust/WASM crypto backend; activated via client.initRustCrypto().http-api/ - Low-level HTTP layer: FetchHttpApi, MatrixHttpApi, error parsing, method enums.models/ - Immutable domain objects: Room, MatrixEvent, User, Device, Thread, RoomMember.matrixrtc/ - Group call plumbing: session management, membership state, LiveKit transport wiring.store/ - Pluggable storage: MemoryStore (default), IndexedDBStore (browser persistence).sync.ts - Drives the /sync polling loop; dispatches events to models and emitters.sliding-sync.ts - MSC3575 sliding sync protocol implementation.secret-storage.ts - SSSS (Secure Secret Storage and Sharing) key management helpers.interactive-auth.ts - Handles Matrix User-Interactive Auth (UIA) flows.oidc/ - OIDC/OAuth2 login and token refresh via oidc-client-ts.rendezvous/ - QR / device-rendezvous login (MSC3906).webrtc/ - Legacy 1:1 WebRTC MatrixCall implementation.pushprocessor.ts - Evaluates push rules against events to determine notification behaviour.timeline-window.ts - Paginated window over a room timeline for efficient rendering.autodiscovery.ts - .well-known/matrix/client lookup and validation.errors.ts - MatrixError, ConnectionError, HTTPError with Matrix-specific fields.logger.ts - loglevel wrapper; use logger.setLevel("debug") to enable verbose output.filter.ts - Construct Filter objects for /sync and /messages to reduce traffic.content-helpers.ts - Builders for m.text, m.image, m.file event content payloads.event-mapper.ts - Converts raw JSON event objects into typed MatrixEvent instances.scheduler.ts - Queues outbound requests with exponential backoff.matrix-js-sdk and a local copy creates two SDK instances; always use a single import path and deduplicate via bundler aliases.experiments: { asyncWebAssembly: true } to webpack.config.js and ensure the .wasm file is served with application/wasm MIME type.getCrypto() returns undefined - You must call await client.initRustCrypto() (or the legacy initCrypto()) before calling startClient; crypto is not auto-initialised."type": "module" in your package.json or use a bundler. Dynamic require() of the package will fail under Node 18+.MatrixError not caught - HTTP errors are thrown asynchronously; always await SDK calls inside a try/catch or attach .catch() to the returned promise.startClient called before login - startClient without a valid accessToken will immediately fail the sync loop; ensure login completes and accessToken is set on the client first.I have the matrix-js-sdk (upstream package: user@example.com) source code
copied into `source/` in my project. There is a USAGE.md file at the root that
describes every public API, import paths, and working TypeScript examples.
My project is a [Node.js / React / Express / describe yours] application written
in TypeScript. I want to [describe your goal, e.g. "build a Matrix bot that
listens for messages and replies", "add a group video call feature using
MatrixRTC", "implement E2E encrypted DMs"].
Please do the following step by step:
1. Read USAGE.md to understand the available exports from source/.
2. Add the required npm dependencies listed in the "Required dependencies" section.
3. Update tsconfig.json as described in "Project setup".
4. Create the integration code, importing only from source/index.ts or the
sub-paths shown in USAGE.md (e.g. source/crypto-api, source/matrixrtc).
5. Follow the "Working examples" in USAGE.md as templates.
6. Check the "Common pitfalls and fixes" section and proactively avoid those issues.
7. Show me the complete files you create or modify.
The source is licensed under the Apache License 2.0. See source/LICENSE if present, or the upstream repository for the full license text.
Upstream package: matrix-js-sdk on npm - maintained by The Matrix.org Foundation C.I.C. and sponsored by Element.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
The full install guide and integration prompts unlock after purchase.
Automation, Utilities & Developer Tools
Free