{"id":11270,"library":"matrix-appservice","title":"Matrix Application Service Framework","description":"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.","status":"active","version":"4.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/matrix-org/matrix-appservice-node","tags":["javascript","matrix-org","typescript"],"install":[{"cmd":"npm install matrix-appservice","lang":"bash","label":"npm"},{"cmd":"yarn add matrix-appservice","lang":"bash","label":"yarn"},{"cmd":"pnpm add matrix-appservice","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary class for running an application service. Prefer ESM imports in modern Node.js environments as of v3.0.0+.","wrong":"const { AppService } = require('matrix-appservice')","symbol":"AppService","correct":"import { AppService } from 'matrix-appservice'"},{"note":"Used for generating registration YAML files. The README example still shows CommonJS for this, but ESM is also supported and preferred. As of v3.0.0+, the library ships TypeScript types and ESM is the idiomatic usage.","wrong":"const AppServiceRegistration = require('matrix-appservice')","symbol":"AppServiceRegistration","correct":"import { AppServiceRegistration } from 'matrix-appservice'"},{"note":"This named export is used for signalling HTTP errors within `onUserQuery` and `onAliasQuery` methods, allowing custom status codes and Matrix error codes. Introduced in v1.1.0.","wrong":"import AppserviceHttpError from 'matrix-appservice'","symbol":"AppserviceHttpError","correct":"import { AppserviceHttpError } from 'matrix-appservice'"}],"quickstart":{"code":"import { AppService, AppServiceRegistration, AppserviceHttpError } from 'matrix-appservice';\nimport * as fs from 'node:fs';\n\n// Step 1: Generate an app service registration file (only needed once)\nconst reg = new AppServiceRegistration();\nreg.setAppServiceUrl('http://localhost:8010');\nreg.setHomeserverToken(AppServiceRegistration.generateToken());\nreg.setAppServiceToken(AppServiceRegistration.generateToken());\nreg.setSenderLocalpart('example-appservice');\nreg.addRegexPattern('users', '@example-.*', true);\nreg.addRegexPattern('aliases', '#example_.*', true);\nreg.setProtocols(['exampleservice']); // For 3PID lookups\nreg.setId('example-service');\n\nconst registrationFilePath = 'registration.yaml';\nreg.outputAsYaml(registrationFilePath);\nconsole.log(`Generated registration file: ${registrationFilePath}`);\n\n// Step 2: Run the app service\nconst as = new AppService({\n  homeserverToken: process.env.HOMESERVER_TOKEN ?? 'your_homeserver_token_here',\n  appServiceToken: process.env.APPSERVICE_TOKEN ?? 'your_appservice_token_here'\n});\n\nas.on('type:m.room.message', (event) => {\n  console.log(`Received message from ${event.sender}: ${event.content.body}`);\n  // Handle the incoming message\n});\n\nas.onUserQuery = async function(userId) {\n  console.log(`Received user query for: ${userId}`);\n  // Example: Validate or create the user\n  if (userId.startsWith('@baduser-')) {\n    throw new AppserviceHttpError(\n      {\n        errcode: 'M_FORBIDDEN',\n        error: 'User query or creation failed for this user ID.'\n      },\n      403\n    );\n  }\n  console.log(`User ${userId} can be created or queried.`);\n  // In a real app, you would provision the user on the AS side here.\n};\n\nas.onAliasQuery = async function(alias) {\n  console.log(`Received alias query for: ${alias}`);\n  // Handle the incoming alias query then respond\n};\n\nconst port = 8010;\nas.listen(port);\nconsole.log(`Matrix Application Service listening on port ${port}`);\nconsole.log('Ensure your homeserver is configured with registration.yaml');\n\n// Optional: Set up TLS if environment variables are present\nif (process.env.MATRIX_AS_TLS_KEY && process.env.MATRIX_AS_TLS_CERT) {\n  console.log('TLS keys found, AppService will attempt to listen with HTTPS.');\n  // AppService.listen handles HTTPS automatically if these env vars are set\n}","lang":"typescript","description":"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."},"warnings":[{"fix":"Upgrade your Node.js runtime to meet the minimum version specified by the package's `engines` field (currently `>=24` for v4.0.1) or downgrade the `matrix-appservice` package to a version compatible with your Node.js runtime.","message":"Node.js version support frequently changes between major versions. Always check the release notes for the exact Node.js requirements. For instance, v4.0.0 dropped support for Node 22 and added support for Node 25. v3.0.0 dropped Node 18 & 20, adding 22 & 24. v2.0.0 dropped Node 16, adding 20. v1.0.0 dropped Node 12, adding 18. Running on an unsupported Node.js version will result in errors.","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Update any custom application service logic that directly interacted with these legacy endpoints to use the Matrix spec-defined paths instead. The framework itself should handle most of this transparently, but custom integrations might be affected.","message":"The legacy `/users`, `/rooms`, and `/transactions` endpoints were removed in v2.0.0 and now redirect to the appropriate spec-compliant paths. Direct calls to these legacy paths will no longer function as expected and will be redirected internally.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Prefer `import { Name } from 'matrix-appservice'` over `const Name = require('matrix-appservice')` for consistency and to leverage TypeScript type definitions and modern tooling. Ensure your `package.json` specifies `\"type\": \"module\"` or use a `.mjs` extension for your application service entry point.","message":"The documentation and examples may mix CommonJS `require()` and ES Modules `import` syntax. While both might technically work depending on your project's configuration, using named `import` statements for all classes (`AppService`, `AppServiceRegistration`, `AppserviceHttpError`) is the recommended modern approach since the library ships TypeScript types and primarily targets ESM environments for recent Node.js versions.","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"Set `MATRIX_AS_TLS_KEY=/path/to/your/key.pem` and `MATRIX_AS_TLS_CERT=/path/to/your/cert.pem` in your environment before starting the application service. Ensure the files are readable by the Node.js process.","message":"To enable HTTPS listening for your application service, you must define the `MATRIX_AS_TLS_KEY` and `MATRIX_AS_TLS_CERT` environment variables. These variables should point to the absolute or relative paths of your TLS key and certificate files, respectively. If these are not set, the application service will default to HTTP.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"When an error condition occurs within `onUserQuery` or `onAliasQuery` that should propagate as a specific HTTP error to the homeserver (e.g., user not found, forbidden), throw an `AppserviceHttpError` instance, providing a Matrix error object and an HTTP status code, like `throw new AppserviceHttpError({ errcode: 'M_FORBIDDEN', error: 'User creation forbidden.' }, 403);`.","message":"Error handling for `onUserQuery` and `onAliasQuery` methods should use `AppserviceHttpError` to return specific HTTP statuses and Matrix error codes. Simply throwing a generic `Error` or returning nothing will result in a default 500 Internal Server Error without a custom Matrix error code.","severity":"gotcha","affected_versions":">=1.1.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"If using CommonJS, ensure you destructure it: `const { AppServiceRegistration } = require('matrix-appservice');`. If using ES Modules, use `import { AppServiceRegistration } from 'matrix-appservice';`.","cause":"Attempting to use `require('matrix-appservice')` as a default import for `AppServiceRegistration` or trying to instantiate it directly when it's a named export, particularly in an ESM context.","error":"TypeError: AppServiceRegistration is not a constructor"},{"fix":"Ensure only one instance of the application service is running. If necessary, change the port it listens on in `as.listen(port)` and update the `appServiceUrl` in your `registration.yaml` accordingly.","cause":"Another process is already using the port that the application service is trying to bind to (e.g., another instance of the app service, or a different web server).","error":"Error: listen EADDRINUSE: address already in use :::8010"},{"fix":"Upgrade your Node.js installation to a version that satisfies the `engines.node` requirement in the `matrix-appservice` package's `package.json` (currently `>=24` for v4.0.1). Use a Node.js version manager like `nvm` or `volta` to easily switch versions.","cause":"The installed Node.js runtime version does not meet the minimum requirement specified by the `matrix-appservice` package.","error":"Error: Your Node.js version is 22.x, but matrix-appservice requires >=24."},{"fix":"Verify that your `registration.yaml` file is correctly uploaded to the homeserver and that its `url` and `as_token` match the `appServiceUrl` and `appServiceToken` you configured in your `AppService` instance. Check homeserver logs for more specific errors related to the app service.","cause":"This often occurs when the application service is not properly configured with the homeserver (e.g., `registration.yaml` is incorrect, `url` is wrong, or `homeserver_token` doesn't match).","error":"Error: Homeserver did not return a valid response to transaction <transaction_id>"}],"ecosystem":"npm"}