Matrix Application Service Framework

4.0.1 · active · verified Sun Apr 19

matrix-appservice is a Node.js framework designed to facilitate the creation of Matrix application services. It provides a web framework agnostic way to quickly set up performant services that can interact with a Matrix homeserver. The current stable version is 4.0.1, released in April 2026. The project maintains a roughly annual major release cadence, primarily driven by updates to Node.js version support and occasional API adjustments. It differentiates itself from more fully-featured SDKs like `matrix-appservice-bridge` by offering a more minimalist, flexible foundation for building application services, focusing on core communication patterns rather than higher-level bridging abstractions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to generate a `registration.yaml` file for your application service and then how to initialize and run the `AppService` instance to listen for incoming Matrix events and handle user/alias queries. It includes an example of using `AppserviceHttpError` for error signaling and notes on optional TLS setup.

import { AppService, AppServiceRegistration, AppserviceHttpError } from 'matrix-appservice';
import * as fs from 'node:fs';

// Step 1: Generate an app service registration file (only needed once)
const reg = new AppServiceRegistration();
reg.setAppServiceUrl('http://localhost:8010');
reg.setHomeserverToken(AppServiceRegistration.generateToken());
reg.setAppServiceToken(AppServiceRegistration.generateToken());
reg.setSenderLocalpart('example-appservice');
reg.addRegexPattern('users', '@example-.*', true);
reg.addRegexPattern('aliases', '#example_.*', true);
reg.setProtocols(['exampleservice']); // For 3PID lookups
reg.setId('example-service');

const registrationFilePath = 'registration.yaml';
reg.outputAsYaml(registrationFilePath);
console.log(`Generated registration file: ${registrationFilePath}`);

// Step 2: Run the app service
const as = new AppService({
  homeserverToken: process.env.HOMESERVER_TOKEN ?? 'your_homeserver_token_here',
  appServiceToken: process.env.APPSERVICE_TOKEN ?? 'your_appservice_token_here'
});

as.on('type:m.room.message', (event) => {
  console.log(`Received message from ${event.sender}: ${event.content.body}`);
  // Handle the incoming message
});

as.onUserQuery = async function(userId) {
  console.log(`Received user query for: ${userId}`);
  // Example: Validate or create the user
  if (userId.startsWith('@baduser-')) {
    throw new AppserviceHttpError(
      {
        errcode: 'M_FORBIDDEN',
        error: 'User query or creation failed for this user ID.'
      },
      403
    );
  }
  console.log(`User ${userId} can be created or queried.`);
  // In a real app, you would provision the user on the AS side here.
};

as.onAliasQuery = async function(alias) {
  console.log(`Received alias query for: ${alias}`);
  // Handle the incoming alias query then respond
};

const port = 8010;
as.listen(port);
console.log(`Matrix Application Service listening on port ${port}`);
console.log('Ensure your homeserver is configured with registration.yaml');

// Optional: Set up TLS if environment variables are present
if (process.env.MATRIX_AS_TLS_KEY && process.env.MATRIX_AS_TLS_CERT) {
  console.log('TLS keys found, AppService will attempt to listen with HTTPS.');
  // AppService.listen handles HTTPS automatically if these env vars are set
}

view raw JSON →