Middleware and Events
Extend the Transport, Endpoint, Service, and collaboration extension modules with general-purpose Middleware and Events.
Middleware and Events are the general-purpose extension points of the Collaboration SDK. Identity and authorization are integrated through Middleware. Middleware validates or restricts an operation before it runs; Events record changes or trigger follow-up work after a state change is confirmed. Both support logging, request tracing, metrics, and derived-state updates.
Two extension moments
| Middleware | Event | |
|---|---|---|
| Runs | During an operation | After a state change is confirmed |
| Can participate in or reject the operation | Yes | No |
| Can enrich call Context | Yes | Reads the Context and result carried by the Event |
| Listener failure | May fail the current operation | Is isolated from the already-determined domain result |
| Typical uses | Identity, authorization, validation, logging, timing | Derived indexes, caches, metrics, in-process notifications |
Use Middleware when you must decide whether an operation can continue. Use an Event when you need only to observe that a state change has already occurred.
Middleware execution model
Middleware for the same Action forms an asynchronous chain in registration order. await next() enters the next Middleware, and the SDK operation runs at the innermost point:
service.use("submitChangeset", async (context, next) => { const startedAt = performance.now(); context.customData.startedAt = startedAt; try { await next(); } finally { metrics.observe("collaboration.submit.duration", performance.now() - startedAt); }});A Middleware can read the Action-specific request, share call-local data through customData, inspect input or query application systems before next(), and record duration or results after next() returns. Throwing a CollabError rejects an expected collaboration operation.
Transport HTTP Middleware may end the HTTP response without calling next(). Service and Endpoint Middleware should reject with an explicit error instead of silently skipping next().
Transport Middleware
transport.use() registers ordinary HTTP Middleware, executed in registration order. Call await next() to continue processing, or end the response directly. transport.useUpgrade() handles WebSocket handshakes.
The following example records HTTP duration, authenticates the request and sets a trusted userID, then registers the Collaboration Endpoint:
transport.use(async (context, next) => { const start = performance.now(); context.response.once("finish", () => { recordHttpDuration({ method: context.incomingMessage.method, route: context.route?.path ?? "unmatched", status: context.response.statusCode, durationMs: performance.now() - start, }); }); await next();});transport.use(async (context, next) => { const user = await authenticate(context.incomingMessage); if (!user) { context.response.statusCode = 401; context.response.end("Authentication required"); return; } context.userID = user.userId; await next();});transport.register(collaborationEndpoint);The application supplies recordHttpDuration and authenticate. The Endpoint uses the userID set by earlier Middleware. The duration observer runs before authentication, so rejected requests are recorded as well.
context.route?.path is the full matched route template, available once execution reaches the Endpoint. Use the response finish event to measure when the response completes. Rejections before routing and unknown paths are recorded as unmatched.
Endpoint Middleware
Endpoint Middleware covers realtime Session and Presence operations:
| Action | Runs | Common uses |
|---|---|---|
connect | After ticket consumption and Session creation, before HELLO | Connection policy, member display name and avatar |
joinUnit | Before a Session joins a Unit Room | Room admission and Unit visibility |
receivePresence | After Presence arrives from a joined Session, before broadcast | Validation and Presence filtering |
sendPresence | Before Presence is sent to each Room member | Per-recipient Presence filtering |
endpoint.use("receivePresence", async (context, next) => { if (JSON.stringify(context.payload).length > 8_000) { throw new CollabError("INVALID_REQUEST", "Presence payload is too large"); } await next();});The Endpoint's session.userID and session.customData come from the HTTP request that issued the Session Ticket. The Endpoint creates memberID for the current WebSocket Session, and this identifier changes after reconnection.
Service Middleware
Service Middleware covers the lifecycle of authoritative collaboration data:
| Action | Boundary | Common uses |
|---|---|---|
readUnitData | Before reading snapshots, blocks, or changesets | Read policy, tenant checks, audit |
createUnit | Before atomically creating a Unit | Type checks, create policy, business rules |
deleteUnits | Before writing a delete batch | Delete policy and per-Unit checks |
recoverUnits | Before writing a recovery batch | Recovery policy and audit |
submitChangeset | After the Service receives a submission, before deduplication and OT | Check edit permissions or limit the size of the submission |
applyChangeset | After OT, before applying the changeset to the document | Validate the transformed operations, for example by checking whether they affect a protected range |
commitChangeset | After applying the changeset to the candidate state, before the Adapter writes it to storage | Set metadata to save with the submission |
service.use("createUnit", async (context, next) => { await creationPolicy.assertAllowed({ userID: context.userID, unitID: context.request.snapshot.unitID, type: context.request.snapshot.type, }); context.customData.creationPolicyChecked = true; await next();});submitChangeset runs once for each logical submission. Revision contention may cause applyChangeset and commitChangeset to run again with a new attempt. Middleware at those stages must be retry-safe and must not send irreversible external messages or perform one-time charges directly.
customData scope
customData carries context within a single call. The caller can supply data, and Middleware can add to it for later Middleware, the Database Adapter, and related Events to read. Typical uses include:
- Passing a tenant ID, a trace ID, or the logger for the request.
- Reusing permission lookup results within the call.
- Recording a start time or an audit label.
The built-in Database Adapters do not persist customData. To save fields together with a document or changeset, see Persistent metadata.
Persistent metadata
metadata stores application-defined data. UnitRecord.metadata is saved with the document, and ChangesetRecord.metadata is saved with each submission.
When creating a document, pass metadata to createUnitFromData() or createUnitFromSnapshot(), or set context.unit.metadata in createUnit middleware. The default is {}.
When submitting a changeset, both metadata objects can be updated in commitChangeset middleware. context.unit.metadata starts with the document’s current metadata, and context.changeset.metadata starts as {}. Their types, UnitMetadata and ChangesetMetadata, are aliases of Record<string, unknown>. Field values must be JSON-serializable.
Update metadata before calling await next(). The following example records the document’s last editor and the source of the submission.
service.use("commitChangeset", async (context, next) => { context.unit.metadata.lastEditorID = context.userID; context.changeset.metadata.source = "application"; await next();});The Service passes both complete objects to the Adapter to save with the submission.
- Revision conflict. When the Service retries, it reruns
commitChangesetmiddleware with the latest Unit metadata and empty changeset metadata. - Duplicate submission. If the same submission already succeeded, the Service returns the original changeset’s metadata.
To read document metadata, call the Adapter’s getUnit() and read metadata from the returned record. For the current submission, read changeset.metadata from the successful submitChangeset() result. For past submissions, call getChangesets(). Each item in the returned changesets array includes metadata.
With the built-in SQLite or PostgreSQL Adapter, document and changeset metadata can also be queried directly with SQL. Use the table and column names defined by that Adapter’s schema.
Event execution model
Services register process-local listeners with on(), which returns a disposable subscription:
const subscription = service.on("changesetCommitted", async (event) => { metrics.increment("collaboration.changeset.committed", { unitType: String(event.changeset.type), }); localCache.delete(event.changeset.unitID);});subscription.dispose();Listeners for the same Event run sequentially in registration order, and the SDK awaits each one. Listener errors are logged and isolated from the already-determined domain result. A failed changesetCommitted listener, for example, does not roll back a changeset that the Adapter has already stored.
Events are appropriate for in-process, recoverable, or non-critical follow-up work. They are not a transaction boundary shared with the database commit, and they do not guarantee delivery to an external system.
Core Service Events
| Event | Confirmed fact | Typical use |
|---|---|---|
unitCreated | The Unit and initial data were created | Local catalog cache or derived index |
changesetCommitted | The Adapter saved the changeset and advanced the revision | Broadcasts, metrics, derived indexes |
unitsDeleted | The Adapter confirmed the deletion batch | Clear process-local related state |
unitsRecovered | The Adapter confirmed the recovery batch | Restore process-local derived state |
In a unitCreated listener, read the document metadata from event.record.metadata. In a changesetCommitted listener, read the submission metadata from event.changeset.metadata.
The Endpoint listens to changesetCommitted on the same Service and broadcasts the confirmed changeset to clients that joined the Unit in the current process. When a pub/sub adapter is configured, the broadcast reaches every node as well. The Endpoint also exposes memberLeftUnit for explicit leave, disconnect, and Endpoint disposal.
Extension modules have independent extension points
History, Thread Comment, and Worktree do not inherit Middleware or Events from the core Collaboration Service:
- History provides read Middleware for
getHistoryList,listHistoryCreators, andgetHistoryChangesets; - Comment provides add, reply, edit, delete, solve, and list Middleware plus
commentCommitted; - Worktree provides lifecycle and draft read/submit/commit Middleware plus creation, status, merge, and draft commit Events.
Install rules separately for each enabled module. Logging, tenant, or authorization Middleware on the core Service does not cover these modules automatically.
Continue with Identity and authorization for a concrete mapping from existing users and ACLs to these general Middleware boundaries.
How is this guide?