{"id":16116,"library":"matrix-js-sdk","title":"Matrix JavaScript SDK","description":"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.","status":"active","version":"41.4.0-rc.0","language":"javascript","source_language":"en","source_url":"https://github.com/matrix-org/matrix-js-sdk","tags":["javascript","matrix-org","typescript"],"install":[{"cmd":"npm install matrix-js-sdk","lang":"bash","label":"npm"},{"cmd":"yarn add matrix-js-sdk","lang":"bash","label":"yarn"},{"cmd":"pnpm add matrix-js-sdk","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"This is the most common pattern for consuming the SDK, providing all exports under a namespace. CommonJS `require` is also supported in Node.js, but ESM `import` is recommended.","wrong":"const sdk = require('matrix-js-sdk');","symbol":"sdk","correct":"import * as sdk from 'matrix-js-sdk';"},{"note":"Many core functions and enums like `createClient`, `ClientEvent`, and `RoomEvent` are named exports. Avoid default imports as there isn't one.","wrong":"import createClient from 'matrix-js-sdk';","symbol":"createClient","correct":"import { createClient, ClientEvent, RoomEvent } from 'matrix-js-sdk';"},{"note":"For TypeScript projects, specific types like `MatrixClient` can be imported using `import type` for better tree-shaking and explicit type usage.","symbol":"MatrixClient","correct":"import type { MatrixClient } from 'matrix-js-sdk';"}],"quickstart":{"code":"import * as sdk from \"matrix-js-sdk\";\nimport { ClientEvent, RoomEvent } from 'matrix-js-sdk';\n\nconst client = sdk.createClient({\n    baseUrl: \"https://matrix.org\",\n    // Store client data in local storage or a custom store\n    // localStorage is often used in browsers, for Node.js consider 'matrix-js-sdk/lib/nodejs-sdk/src/node-crypto-store'\n    store: new sdk.MemoryStore(), \n    // For E2E, a crypto store is essential\n    cryptoStore: new sdk.MemoryCryptoStore(), \n});\n\nclient.once(ClientEvent.SYNC_STATE, async (state, prevState, res) => {\n    if (state === \"PREPARED\") {\n        console.log(\"Client prepared and synced.\");\n\n        // Example: Listen for new messages\n        client.on(RoomEvent.Timeline, function (event, room, toStartOfTimeline) {\n            if (event.getType() !== \"m.room.message\" || toStartOfTimeline) {\n                return; // Only process new messages, not historical ones on initial sync\n            }\n            console.log(`[${room.name || room.roomId}] <${event.getSender()}> ${event.getContent().body}`);\n        });\n\n        // Example: Get public rooms\n        client.publicRooms(function (err, data) {\n            if (err) {\n                console.error(\"Error fetching public rooms:\", err);\n                return;\n            }\n            console.log(\"Public Rooms:\", data.chunk.map(r => r.name));\n        });\n\n        // To send a message (requires authentication and a joined room)\n        // const roomId = \"!yourroomid:matrix.org\";\n        // const content = {\n        //     body: \"Hello from matrix-js-sdk!\",\n        //     msgtype: \"m.text\",\n        // };\n        // try {\n        //     await client.sendEvent(roomId, \"m.room.message\", content, \"\");\n        //     console.log(\"Message sent!\");\n        // } catch (e) {\n        //     console.error(\"Error sending message:\", e);\n        // }\n\n    } else {\n        console.log(`Sync state changed to: ${state}`);\n    }\n});\n\nconsole.log(\"Starting client...\");\nclient.startClient({\n    initialSyncLimit: 10,\n    // Set `syncFromTokens` to `false` for new clients, `true` for resuming existing sessions\n    syncFromTokens: false,\n}).catch(e => console.error(\"Failed to start client:\", e));","lang":"typescript","description":"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."},"warnings":[{"fix":"Consult the official Matrix Specification v1.13 release notes and the `matrix-js-sdk` changelog for detailed migration paths. Update client code to align with any changed API behaviors or data formats.","message":"Version 41.0.0 introduced support for Matrix Specification v1.13, which may involve breaking changes to API endpoints or expected data structures due to underlying spec updates. Developers should review the Matrix spec changes for v1.13 and test their applications thoroughly when upgrading from pre-v41.0.0 versions.","severity":"breaking","affected_versions":">=41.0.0"},{"fix":"Regularly monitor the Matrix specification development and keep `matrix-js-sdk` updated to avoid relying on features that may be deprecated or removed. Plan for periodic updates and compatibility checks.","message":"The SDK guarantees feature support for at least 4 Matrix spec releases. Features removed from the Matrix spec may be eligible for removal from the SDK after this grace period, even without being explicitly marked as 'breaking changes' in the SDK's changelog. This means long-term applications might need to periodically review their usage of older Matrix features.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Refer to the 'Authenticated Media' section in the `matrix-js-sdk` documentation to properly enable support for authenticated media, which usually involves providing appropriate credentials or configuring the client's HTTP handlers.","message":"Using authenticated media endpoints requires explicit configuration. If not configured, requests for media (images, files, avatars) might fail or result in unauthenticated access errors.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure a `cryptoStore` (e.g., `MemoryCryptoStore` for testing, persistent storage for production) is passed to `createClient`. Follow the E2E setup guide in the SDK's documentation for full details on device management, key backups, and verification processes.","message":"End-to-End Encryption (E2E) support is robust but not enabled by default and requires proper setup, including providing a `cryptoStore` during client creation. Incorrect or incomplete E2E setup can lead to message decryption failures or inability to participate in encrypted rooms.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Upgrade your Node.js environment to version 22.0.0 or newer. Consider using a Node.js version manager like `nvm` to easily switch between versions.","message":"The SDK requires Node.js version 22.0.0 or higher for Node.js environments. Using older Node.js versions may lead to unexpected errors, build failures, or runtime inconsistencies.","severity":"gotcha","affected_versions":"<41.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Ensure `import { createClient } from 'matrix-js-sdk';` or `import * as sdk from 'matrix-js-sdk';` is used and `sdk.createClient({...})` is called with valid configuration parameters.","cause":"The `client` object was not correctly initialized, or `createClient` did not return a valid instance. This can happen if `createClient` fails or is not correctly imported.","error":"TypeError: client.publicRooms is not a function"},{"fix":"Ensure your Node.js environment is configured correctly. If you're encountering this, you might be using an outdated version of `matrix-js-sdk` in Node.js, or trying to use a browser-specific build. Check the SDK's documentation for Node.js setup specifics, which might involve configuring a Node.js-specific HTTP client.","cause":"Attempting to run browser-specific code in a Node.js environment without appropriate polyfills or a custom HTTP client configured. `matrix-js-sdk` by default tries to detect the environment.","error":"Error: XMLHttpRequest is not defined"},{"fix":"Check your `baseUrl` for correctness. Verify network connectivity to the Matrix home server. If using authentication, ensure user ID and access token are valid. Inspect the `res` object passed to the `ClientEvent.sync` listener for more specific error details from the server.","cause":"The client failed to complete its initial sync or encountered a persistent error during synchronization with the Matrix home server. This can be due to network issues, invalid credentials, server errors, or misconfigured `baseUrl`.","error":"Error: Sync state: ERROR"},{"fix":"Ensure `cryptoStore` is provided during `createClient` initialization. Verify all participating devices in the room are cross-signed and trusted. If a device is new, it might need to wait for key sharing or be verified. Check key backups if applicable.","cause":"This common error in E2E-enabled rooms indicates that the client could not decrypt an incoming message. Reasons include missing encryption keys, unverified devices, corrupted device lists, or an improperly configured `cryptoStore`.","error":"Failed to decrypt message"}],"ecosystem":"npm"}