matter.js is a comprehensive TypeScript implementation of the Matter/Thread smart home protocol. This is a monorepo containing multiple packages that work together to provide Matter protocol support for JavaScript/TypeScript applications.
@matter/general- Core utilities, crypto, networking abstractions@matter/protocol- Matter protocol implementation, commissioning, clustering@matter/model- Matter data model, cluster definitions, device types@matter/node- Node/endpoint implementations, behaviors, supervision@matter/types- TypeScript type definitions for Matter clusters and data types
@matter/nodejs- Node.js platform implementation@matter/nodejs-ble- Bluetooth Low Energy support for Node.js@matter/nodejs-shell- Interactive shell for Matter operations
@matter/main- Main entry point package@matter/examples- Example applications and devices@matter/create- Project scaffolding tool@project-chip/matter.js- Legacy compatibility package
packages/tools- Build system, documentation generation, project managementsupport/codegen- Code generation from Matter specificationssupport/chip-testing- Integration with Project CHIP/connectedhomeip for testing
This project heavily uses code generation:
- Clusters are generated from Matter specifications in
support/codegen/src/clusters/ - Use
ClusterFile,ClusterComponentGeneratorfor cluster definitions - Generated files follow pattern:
src/clusters/[ClusterName].ts
- Device endpoints generated in
support/codegen/src/endpoints/ - Use
EndpointFile,RequirementGeneratorfor device type definitions - Generated files follow pattern:
src/endpoints/[DeviceType].ts
- Re-export generation in
support/codegen/src/forwards/ - Creates proxy modules for clean package boundaries
- Generated files include header:
/*** THIS FILE IS GENERATED, DO NOT EDIT ***/ - Pattern for main package forwards:
packages/main/src/forwards/[category]/[name].ts
- Core abstraction for endpoint functionality in
@matter/node - Extend
Behaviorclass for cluster implementations - Use
@behaviordecorator for registration - File pattern:
src/behaviors/[cluster-name]/[ClusterName]Behavior.ts
Environmentprovides platform-specific runtime services registered by each platform (Node.js, React Native, etc.)- Access the default environment for your platform using
Environment.default - Create
ServerNodeinstances for Matter devices:const server = await ServerNode.create({ id: "unique-device-id", network: { port: 5540 }, commissioning: { passcode: 20202021, discriminator: 3840 }, // ... other config });
- Add endpoints to nodes:
await server.add(endpoint); - Start the server non-blocking:
await server.start();(resolves when online) - Run the server blocking:
await server.run();(resolves when server shuts down) - See
examples/device-onoff-advanced/src/DeviceNodeFull.tsfor comprehensive examples
- Use
ClusterModel,DeviceTypeModel,AttributeModeletc. from@matter/model - Models represent Matter specification elements
- Support variance analysis for conditional features
- Extensive use of TypeScript generics and conditional types
- IMPORTANT: Requires at least
"strictNullChecks": trueor preferably"strict": true - Base TypeScript configuration in
packages/tools/tsc/tsconfig.base.jsonuses"strict": true - Schema validation with
Schemaclasses
nacho-build- Build packages and documentationnacho-run- Execute TypeScript files with automatic transpilation and source mapsmatter-test- Run tests across workspace packagesmatter-create- Scaffolding tool for new Matter.js projectsmatter-version- Version management tool
The repository includes ready-to-run example applications:
npm run matter-device # Simple on/off device
npm run matter-bridge # Bridge with multiple devices
npm run matter-composeddevice # Composed device example
npm run matter-multidevice # Multiple device example
npm run matter-controller # Controller example
npm run shell # Interactive Matter shellUse nacho-run to execute any TypeScript example directly:
nacho-run examples/device-onoff/src/DeviceNode.ts
nacho-run examples/controller/src/ControllerNode.ts- Minimum required:
"strictNullChecks": true - Recommended:
"strict": truefor best type safety - Module settings:
"module": "node16","moduleResolution": "node16" - Target:
"es2022"minimum - Key settings from base config:
{ "compilerOptions": { "strict": true, "target": "es2022", "module": "node16", "moduleResolution": "node16", "composite": true, "esModuleInterop": true, "noImplicitAny": true, "noImplicitOverride": true, "isolatedModules": true } }
- All packages use TypeScript project references
- Managed automatically by build tools in
packages/tools/src/building/tsconfig.ts - Incremental compilation via
"composite": true - Separate configs for lib, app, and test builds
- Monorepo managed with custom build tools in
packages/tools - Use
nacho-buildcommand for building packages (via node_modules/.bin/) - Custom
nacho-runfor executing TypeScript files with source maps - Custom
matter-testfor running tests across packages - Support for ESM and CommonJS outputs
- TypeScript project references for incremental builds
npm run build # Build all packages
npm run build-clean # Clean build and rebuild all packages
npm run build-doc # Generate documentation
npm run clean # Clean all build outputs
nacho-build # Direct build tool (via node_modules/.bin/nacho-build)Code generation is handled through TypeScript files in support/codegen/src/:
# Run code generation scripts with nacho-run
nacho-run support/codegen/src/generate-spec.ts # Generate from Matter spec
nacho-run support/codegen/src/generate-clusters.ts # Generate cluster definitions
nacho-run support/codegen/src/generate-endpoints.ts # Generate endpoint definitions
nacho-run support/codegen/src/generate-forwards.ts # Generate forward exports
nacho-run support/codegen/src/generate-model.ts # Generate data models
nacho-run support/codegen/src/generate-vscode.ts # Generate VS Code configuration- Use custom
matter-testframework (not Jest directly) - Test files:
*.test.tsalongside source files - Run tests with
npm run testormatter-test -w - Mock external dependencies, especially platform-specific code
- Tests are run for ESM, CJS, and web (when Playwright is installed) module formats
matter-test [options] [command]
Commands:
esm # Run tests on Node.js (ES6 modules)
cjs # Run tests on Node.js (CommonJS modules)
web # Run tests in web browser
report # Display details about tests
manual # Start web test server for manual testing
Options:
-p, --prefix <dir> # Directory of package to test (default: ".")
-w, --web # Enable web tests in default test mode
--spec <paths> # One or more test paths (default: "./test/**/*{.test,Test}.ts")
--all-logs # Emit log messages in real time
--debug # Enable Mocha debugging
-e, --environment <name> # Select named test environment
-f, --fgrep <string> # Only run tests matching this string
--force-exit # Force Node to exit after tests complete
-g, --grep <regexp> # Only run tests matching this regexp
-i, --invert # Inverts --grep and --fgrep matches
--profile # Write profiling data to build/profiles (Node only)
--wtf # Enlist wtfnode to detect test leaks
--trace-unhandled # Detail unhandled rejections with trace-unhandled
--clear # Clear terminal before testing
--report # Display test summary after testing
--pull # Update containers before testing (default: true)- Device commissioning and interaction tests in
support/tests - Use
@matter/examplesfor test scenarios - CHIP tool integration for interoperability testing
- Located in
support/chip-testingpackage
npm run test # Run all tests in workspace
matter-test -w # Run tests with workspace scanning
matter-test <package> # Run tests for specific package- One main export per file
- Use barrel exports (
index.ts) for public APIs - Separate internal utilities with
.internal.tssuffix
- PascalCase for classes, interfaces, types
- camelCase for functions, variables, properties
- SCREAMING_SNAKE_CASE for constants
- PascalCase for files containing a major class, otherwise kebab-case
// Prefer specific imports with package aliases (when available in package)
import { ClusterModel } from "#model";
// Use type-only imports when possible with package aliases
import type { Cluster } from "#types";
// External package imports
import { ClusterModel } from "@matter/model";
import type { Cluster } from "@matter/types";
// Internal imports use relative paths with .js extension
import { someUtility } from "./utils.js";
// Platform imports
import "@matter/main/platform"; // Must be imported first for platform setup
export * from "@matter/node/behaviors";- Use specific error classes:
CommissioningError,ConstraintError, etc. - Provide detailed error messages with context
- Use
MatterErroras base class for Matter-specific errors
- Prefer
async/awaitover Promises - Use
usingfor resource management where applicable - Handle cancellation with
AbortSignalwhen appropriate
- Implement server behaviors for device functionality
- Use feature flags for conditional cluster elements
- Support both mandatory and optional cluster features
- Follow Matter commissioning flow patterns
- Handle network credentials securely
- Support both WiFi and Thread network setup
- Use TLV (Tag-Length-Value) encoding for Matter data
- Implement proper schema validation
- Support fabric-scoped data handling
- Use JSDoc for all public APIs
- Include
@seereferences to Matter specification sections - Document cluster conformance requirements
- Provide working examples in
@matter/examples - Include both device and controller examples
- Document setup and usage instructions
- Use platform abstractions from
@matter/general - Implement platform-specific code in
@matter/nodejs - Support both CommonJS and ESM module systems
- Avoid Node.js-specific APIs in core packages
- Use dependency injection for platform services
- Test on multiple Node.js versions (20.x, 22.x, 24.x)
- Use lazy initialization for expensive operations
- Cache cluster definitions and models
- Minimize memory allocations in hot paths
- Use efficient data structures for large datasets
- Destructure variables from data objects when used more than once to optimize object key lookups
- Handle cryptographic operations through
@matter/general/crypto - Validate all input data with schemas
- Implement proper access control for cluster operations
- Follow Matter security requirements for commissioning
MANDATORY: All PRs must be verified by running the following commands to prove the changes work correctly:
- Build verification:
npm run build- Must complete successfully without errors - Lint verification:
npm run lint- Must pass with no linting issues - Format verification:
npm run format-verify- Must pass with no formatting issues (runnpm run formatto fix any issues) - Test verification:
npm run test- Must pass all relevant tests (ESM/CJS tests required, web tests optional if Playwright setup unavailable)
Alternative test commands if web tests fail due to missing browser setup:
node packages/testing/bin/test.js esm- Run ESM tests onlynode packages/testing/bin/test.js cjs- Run CJS tests only
Note: Web tests may still fail if Playwright browsers cannot be installed due to firewall or download issues. The core ESM and CJS tests provide sufficient verification of functionality.
Document verification results in the PR comment to demonstrate that all changes have been properly tested.