Skip to main content

Overview

createClient is the recommended entry point for instantiating a MatrixClient. Unlike calling new MatrixClient() directly, it automatically provisions default implementations for the store, scheduler, and cryptoStore dependencies when they are not supplied.
import { createClient } from "matrix-js-sdk";

const client = createClient(opts: ICreateClientOpts): MatrixClient;
Source: src/matrix.ts:148

Function Signature

export function createClient(opts: ICreateClientOpts): MatrixClient
opts
ICreateClientOpts
required
Configuration options. All properties of ICreateClientOpts are passed directly to the MatrixClient constructor.
MatrixClient
MatrixClient
A new, fully configured MatrixClient instance. Call startClient() to begin syncing.

ICreateClientOpts Reference

Connection

baseUrl
string
required
The base URL of the homeserver, e.g. "https://matrix.org". Must not have a trailing slash.
idBaseUrl
string
The base URL of the identity server, e.g. "https://vector.im".
fetchFn
typeof globalThis.fetch
A custom fetch implementation. Falls back to the global fetch if not provided.
localTimeoutMs
number
Default maximum time in milliseconds to wait before timing out HTTP requests. No timeout by default.
useAuthorizationHeader
boolean
Send the access token as an Authorization: Bearer header rather than a query parameter. Default: true. Note: query-parameter access tokens are deprecated as of Matrix spec v1.11.
queryParams
QueryDict
Extra query parameters appended to all requests. Useful for application services that require ?user_id=.

Authentication

accessToken
string
The access token for the user’s session. Required for most API calls.
refreshToken
string
An OIDC refresh token, if applicable. Used by tokenRefreshFunction to renew accessToken.
tokenRefreshFunction
TokenRefreshFunction
A callback invoked by the HTTP layer when a potentially expired token is encountered and a refreshToken is available.
userId
string
The MXID of the logged-in user, e.g. "@alice:matrix.org". Required for most authenticated operations.
deviceId
string
A unique identifier for this device. Required to enable end-to-end encryption. Must be consistent across sessions for the same device.

Storage

store
Store
The sync data store. If not specified, createClient provisions a MemoryStore (with localStorage in browsers). To persist data across sessions use IndexedDBStore.
cryptoStore
CryptoStore
A store for end-to-end crypto session data. createClient uses the factory registered via setCryptoStoreFactory(), or a MemoryCryptoStore if no factory is set. Required when migrating a device from legacy crypto to Rust crypto.
pickleKey
string
An encryption key used to protect sensitive data (e.g. E2EE keys) in the cryptoStore. Must be the same value every time the client is initialised for the same device. Only used by the legacy crypto implementation.

Scheduling

scheduler
MatrixScheduler
The event scheduler. If not specified, createClient creates a default MatrixScheduler. Without a scheduler, failed requests will not be retried.

Cryptography

cryptoCallbacks
CryptoCallbacks
Application-provided callbacks for cryptographic operations, such as prompting the user for cross-signing keys or secret storage passphrases.
verificationMethods
string[]
The interactive verification methods to offer when verifying another device. If unset, all known methods (QR code display, QR code scan, SAS/emojis) are offered.
enableEncryptedStateEvents
boolean
Enable encrypted state events (experimental).

Identity Server

identityServer
IIdentityServerProvider
A provider object with a getAccessToken() method. Used to authenticate calls to the identity server without manually managing identity server access tokens.

Timeline

timelineSupport
boolean
Enable improved timeline support, required for getEventTimeline(). Disabled by default for compatibility with older clients. Set to true for modern applications.

Room Display

roomNameGenerator
(roomId: string, state: RoomNameState) => string | null
A callback to generate room names for empty or membership-derived room names. Defaults to a built-in English handler with basic pluralisation.

VoIP / Group Calls

forceTURN
boolean
Force all WebRTC calls to relay through a TURN server. Default: false.
iceCandidatePoolSize
number
Number of ICE candidates to gather on incoming call before signalling begins. Default: 0.
supportsCallTransfer
boolean
Advertise support for call transfers. Default: false.
fallbackICEServerAllowed
boolean
Allow a fallback ICE server when the homeserver provides none. Default: false.
useE2eForGroupCall
boolean
Encrypt to-device signalling for group calls with Olm. Default: true.
useLivekitForGroupCalls
boolean
Use LiveKit media at the application layer instead of the built-in WebRTC stack. Group calls will only create signalling events.
isVoipWithNoMediaAllowed
boolean
Allow joining group calls without an active media stream. Default: false.
disableVoip
boolean
Disable VoIP support entirely (prevents fetching TURN servers, etc.). Default: false.

Logging

logger
Logger
A custom logger for this MatrixClient instance. Defaults to the global logger. Use DebugLogger for verbose output.

Usage Examples

import { createClient } from "matrix-js-sdk";

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

await client.startClient();

With a persistent store

import { createClient, IndexedDBStore } from "matrix-js-sdk";

const store = new IndexedDBStore({
  indexedDB: globalThis.indexedDB,
  dbName: "my-app-matrix",
  localStorage: globalThis.localStorage,
});
await store.startup();

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

await client.startClient({ lazyLoadMembers: true });

With Rust Crypto (E2EE)

import { createClient } from "matrix-js-sdk";

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

// Initialise the Rust crypto backend before starting sync
await client.initRustCrypto();
await client.startClient();

createRoomWidgetClient()

Construct a MatrixClient that operates inside a Matrix widget. This client communicates with the host client via the Matrix Widget API rather than directly with a homeserver, and therefore has a restricted feature set.
export function createRoomWidgetClient(
  widgetApi: WidgetApi,
  capabilities: ICapabilities,
  roomId: string,
  opts: ICreateClientOpts,
  sendContentLoaded?: boolean,
): MatrixClient
Source: src/matrix.ts:166
widgetApi
WidgetApi
required
The WidgetApi instance from matrix-widget-api used for communication between the widget and the host client.
capabilities
ICapabilities
required
The capabilities the widget client will request from the host client.
roomId
string
required
The ID of the room the widget is associated with.
opts
ICreateClientOpts
required
Standard client options (at minimum baseUrl).
sendContentLoaded
boolean
Whether to send a ContentLoaded widget action immediately after setup. Set to false if waitForIFrameLoad=true is used, or if the widget wants to send ContentLoaded at a later time. Default: true.
MatrixClient
MatrixClient
A RoomWidgetClient instance (subclass of MatrixClient) with restricted capabilities.
import { createRoomWidgetClient } from "matrix-js-sdk";
import { WidgetApi } from "matrix-widget-api";

const widgetApi = new WidgetApi();

const client = createRoomWidgetClient(
  widgetApi,
  { sendEvent: ["m.room.message"], receiveEvent: ["m.room.message"] },
  "!abc123:matrix.org",
  { baseUrl: "https://matrix.org" },
);

Build docs developers (and LLMs) love