DOCX collaboration reference
Configure Pro collaboration providers, server rooms, presence, recovery, and limits.
This reference covers Pro collaboration providers, server rooms, presence, recovery, and limits. For a first setup, see the real-time collaboration quickstart.
The collaboration module from @docx-editor.dev/pro replicates the full DOCX package through Yjs. Without the module, the editor attaches no replica, local undo stays active, and snapshot().collaborationStatus is 'inactive'.
Before you deploy, add client admission checks and saved-room validation. For both, see Collaboration versions and upgrades.
Install the packages
Install Pro, Yjs, and your provider:
npm install @docx-editor.dev/pro yjs y-webrtc # WebRTC
npm install @docx-editor.dev/pro yjs @hocuspocus/provider # Hocuspocusyjs, y-webrtc, and @hocuspocus/provider are optional Pro peer dependencies. Pro installs y-protocols.
| Entry | Exports |
|---|---|
@docx-editor.dev/pro/{react,vue}/webrtc | useWebrtcCollaboration. A subpath keeps the provider out of other bundles. |
@docx-editor.dev/pro/{react,vue}/hocuspocus | useHocuspocusCollaboration |
@docx-editor.dev/pro/{react,vue} | DocxEditorCollaborationRoot, DocxEditorCollaboration, useCollaborationStatus, useCollaborationParticipants, useDocumentCollaboration, and the CollaborationSession, CollaborationStatus, and CollaborationFailure types |
@docx-editor.dev/pro | collaborationModule, without a network provider |
@docx-editor.dev/pro/collaboration | Yjs factories and server helpers |
@docx-editor.dev/pro/collaboration/webrtc | createWebrtcCollaboration, DEMO_SIGNALING_ENDPOINTS, createCollaborationRoomId |
@docx-editor.dev/pro/collaboration/hocuspocus | createHocuspocusCollaboration |
Connect with useWebrtcCollaboration
The hook owns a WebRTC room. It creates the replica, builds modules, and destroys the room when you leave:
import { useRef } from 'react';
import { DocxEditor, type DocxEditorRef } from '@docx-editor.dev/react';
import { DEMO_SIGNALING_ENDPOINTS } from '@docx-editor.dev/pro/collaboration/webrtc';
import { useWebrtcCollaboration } from '@docx-editor.dev/pro/react/webrtc';
type Props = { roomId: string; bytes: Uint8Array; actorId: string; name: string };
export function CollaborativeEditor({ roomId, bytes, actorId, name }: Props) {
const editorRef = useRef<DocxEditorRef>(null);
const { document, modules, session, error, leave } = useWebrtcCollaboration({
room: {
roomId,
identity: { actorId, name },
bootstrap: { kind: 'create-or-join', document: bytes },
// Demo only. Pass your own signaling URLs in production.
signaling: DEMO_SIGNALING_ENDPOINTS,
},
});
async function leaveRoom() {
// `leave` requires current bytes. The hook cannot read them.
const saved = await editorRef.current?.save();
if (saved) leave(new Uint8Array(saved));
}
if (!document) return <p>{error ? 'Could not join.' : 'Connecting…'}</p>;
return (
<>
{error && <p role="alert">Save a copy before you reconnect.</p>}
<button type="button" onClick={leaveRoom}>
Leave
</button>
<DocxEditor ref={editorRef} key={session?.sessionId} document={document} modules={modules} />
</>
);
}In Vue, import from @docx-editor.dev/pro/vue/webrtc and pass the options as a getter, such as useWebrtcCollaboration(() => ({ room })).
| Field | Description |
|---|---|
document | Room bytes. null until the room joins. |
modules | Your modules plus collaborationModule. Pass them to the editor. |
session | CollaborationSession with identity, status, presence, and undo. No attach or gateOperations. |
error | CollaborationFailure for an initial or later failure, such as an expired token, concurrent-seed, or a digest mismatch. |
connect(options) | Opens a room. Resolves to a CollaborationFailure, or null on success. |
leave(bytes) | Leaves the room. Pass the current bytes from save(). |
rejoin(bytes) | Leaves with saved bytes, then joins the same room with { kind: 'join' }. Resolves like connect. Throws before any connection attempt. |
ydoc, provider | null before the first connection. For persistence or direct provider access. |
unsyncedChanges | Edits that have not reached the room. See Edit offline. |
- Give each peer a unique
actorId, including each tab of one user. - Set
keytosession?.sessionId. The editor readsmodulesonly at construction, so withoutkey, edits do not replicate. - Pass review and custom-node modules through the hook's
modulesoption. A second collaboration module throws. - Branch on
error.code, never on message text. Handleerroreven whendocumentis set. - Omit
roomto connect later withconnect. That room stays open untilleave. - Changing the room, server, bootstrap kind, or
actorIdinroomreconnects;room: nullleaves. Save local work first.
Choose a bootstrap
bootstrap.kind | Behavior |
|---|---|
create-or-join | The first peer seeds the empty room from document. Later peers join. Every peer uses the same settings. |
create | Seeds the room. On Hocuspocus, it waits for server state, then fails with already-initialized if the room is seeded, or initialization-timeout after syncedTimeoutMs. |
join | Joins a seeded room. Use it when a server seeds rooms. |
If two isolated peers seed one room at once, each replica reports concurrent-seed. Create a new room from saved bytes.
Use your own signaling
WebRTC peers find each other through signaling servers. In production, pass your own signaling and TURN (Traversal Using Relays around NAT) servers:
const room: UseWebrtcCollaborationConnectOptions = {
roomId,
identity: { actorId, name },
bootstrap: { kind: 'create-or-join', document: bytes },
signaling: ['wss://signaling.example.com'],
iceServers: [{ urls: 'turn:turn.example.com:3478', username, credential }],
};The same options apply to connect and createWebrtcCollaboration. Many networks block WebRTC without TURN.
signaling value | Result |
|---|---|
Your ws:// or wss:// URLs | Production setup. |
DEMO_SIGNALING_ENDPOINTS | Shared, unauthenticated public service. It receives every room ID, and without a password, signaling messages in plaintext. Demos only. |
[] | No signaling. Only tabs of the same browser connect. |
| Omitted or invalid | No connection opens. createWebrtcCollaboration rejects with a TypeError. connect and the room option set error to a transport failure. |
signaling is required. Since 2.31.0, an omitted value does not select public servers. To recover, call connect with corrected options; rejoin reuses the old ones.
Each room uses only the URLs it lists. After the first room opens, this covers every y-webrtc provider on the page. For a provider created earlier, call disconnect() before destroy().
Connect to a Hocuspocus server
useHocuspocusCollaboration has the same return values and lifecycle as the WebRTC hook. Pass the server URL and a token:
const { document, modules, session, error } = useHocuspocusCollaboration({
room: {
url: 'wss://collab.example.test',
roomId,
token,
identity: { actorId, name },
bootstrap: { kind: 'create-or-join', document: bytes },
},
});If your server seeds rooms, pass bootstrap: { kind: 'join' }. See Seed new rooms on a server.
| Option | Description |
|---|---|
url | Hocuspocus server URL. |
token | String, or callback that returns the latest credential, called on each reconnection. It reaches the server's onAuthenticate. A changed string does not reconnect; use a callback to renew. |
syncedTimeoutMs | Initial sync limit. Default 30 seconds. Fails with initialization-timeout. |
bootstrap.signal | Covers the whole join, including the server's room load. Fails with initialization-aborted. |
offlineEditing | false refuses edits while disconnected. Every room factory and hook accepts it. |
- Recognized server failure codes pass through. New credentials cannot fix
collaboration-format-mismatch. - Other authentication refusals fail with
initialization-abortedduring the join, orauthentication-failedafter it, with the reason indetail. createHocuspocusCollaborationtakes the same options and returns the room,ydoc, andprovider.- The Hocuspocus v4 server runs on Node, not Bun. Use
@hocuspocus/providerfor the required authentication handshake.
Mount the editor
DocxEditorCollaborationRoot sets key, document, and modules from the room. It uses the identity name as author, and passes other DocxEditor.Root props through:
import { DocxEditor } from '@docx-editor.dev/react';
import { DocxEditorCollaboration, DocxEditorCollaborationRoot } from '@docx-editor.dev/pro/react';
import {
useHocuspocusCollaboration,
type UseHocuspocusCollaborationConnectOptions as Room,
} from '@docx-editor.dev/pro/react/hocuspocus';
export function CollaborativeEditor({ room }: { room: Room }) {
const collaboration = useHocuspocusCollaboration({ room });
return (
<DocxEditorCollaborationRoot
collaboration={collaboration}
fallback={<p>{collaboration.error ? 'Could not connect.' : 'Connecting…'}</p>}
>
<DocxEditor.Toolbar />
<DocxEditor.Viewport>
<DocxEditor.Content />
<DocxEditorCollaboration.CaretLabels />
</DocxEditor.Viewport>
</DocxEditorCollaborationRoot>
);
}<script setup lang="ts">
import { reactive } from 'vue';
import { DocxEditor } from '@docx-editor.dev/vue';
import { DocxEditorCollaboration, DocxEditorCollaborationRoot } from '@docx-editor.dev/pro/vue';
import {
useHocuspocusCollaboration,
type UseHocuspocusCollaborationConnectOptions,
} from '@docx-editor.dev/pro/vue/hocuspocus';
const props = defineProps<{ room: UseHocuspocusCollaborationConnectOptions }>();
// Composables return refs. Wrap the return with `reactive`.
const collaboration = reactive(useHocuspocusCollaboration(() => ({ room: props.room })));
</script>
<template>
<DocxEditorCollaborationRoot :collaboration="collaboration">
<DocxEditor.Toolbar />
<DocxEditor.Viewport>
<DocxEditor.Content />
<DocxEditorCollaboration.CaretLabels />
</DocxEditor.Viewport>
<template #fallback>
<p>{{ collaboration.error ? 'Could not connect.' : 'Connecting…' }}</p>
</template>
</DocxEditorCollaborationRoot>
</template>- The root renders
fallbackwhiledocumentisnull. In Vue, it renders nothing without the slot. - Show
errorbeside an existing editor, and keep the editor mounted so users can save local work. - Children of the root, such as custom controls, find the session without a
sessionargument. - Let the room hook manage cleanup. An effect cleanup can destroy the room before React StrictMode remounts.
To mount two rooms on one page, or bytes from elsewhere, use DocxEditor.Root directly. Pass key={session?.sessionId}, the room's document, and its modules together, or the editor works but does not replicate.
Show status and presence
useCollaborationStatus() returns these fields:
| Field | Description |
|---|---|
status | Session state, or inactive without a session. |
reason | Cause of the present state, such as a failing WebRTC link while ready. Clears after recovery. |
lastFailure | Latest error failure. Not set by a ready or disconnected reason. |
live | Edits made now reach the room. |
diverged | destroyed, or an error that does not heal. Offer rejoin. |
recovering | error that the next update heals. Show a short notice, not a rejoin action. |
waiting | Edits wait for an update they depend on. The editor refuses edits until it arrives. |
failureCount | Number of recorded failures. Changes on each failure, even with the same code. |
attached | An editor attached its port. Live but unattached usually means the editor did not remount. |
useCollaborationParticipants() returns the participants. Both hooks and the presence parts take an optional session; the default is the editor's session. With your own Yjs resources, use useDocumentCollaboration.
Show the room status
DocxEditorCollaboration.Status shows a translated notice when the room needs attention. Pass onRejoin (Vue: @rejoin) to show a Rejoin button:
// Implement a confirmed download or durable storage. Reject on failure.
declare function preserveRecoveryCopy(bytes: Uint8Array): Promise<void>;
async function rejoinRoom() {
const saved = await editorRef.current?.save();
if (!saved) return;
const bytes = new Uint8Array(saved);
await preserveRecoveryCopy(bytes);
await rejoin(bytes);
}
<DocxEditorCollaboration.Status onRejoin={rejoinRoom} />;| State | Rejoin button |
|---|---|
| Connecting, offline, or catching up on an update | No |
| Edits wait for the latest room changes | After 10 seconds |
| The room refused an edit, and the editor undid it | No |
| Out of sync | Yes, if you handle rejoin |
| Upgrade required: client and room formats differ | No |
| New room required: merged seeds, a damaged stored file, or a resource limit | No |
An empty role="status" region stays mounted, so screen readers announce each message. A custom render function (React) or default slot (Vue) receives kind, the translated message, and an optional rejoin. CSS hooks: the docx-collaboration-status class and data-collaboration-status attribute.
Show avatars and caret labels
DocxEditorCollaboration.Avatars renders participant initials, local participant first. DocxEditorCollaboration.CaretLabels replaces each remote caret label; the engine positions and colors it:
<DocxEditorCollaboration.Avatars max={4} />
<DocxEditorCollaboration.CaretLabels>
{({ selection, participant, color, avatarUrl }) => (
<MyLabel name={participant?.name ?? selection.name} color={color} avatarUrl={avatarUrl} />
)}
</DocxEditorCollaboration.CaretLabels><DocxEditorCollaboration.Avatars :max="4" />
<DocxEditorCollaboration.CaretLabels v-slot="{ selection, participant, color, avatarUrl }">
<MyLabel :name="participant?.name ?? selection.name" :color="color" :avatar-url="avatarUrl" />
</DocxEditorCollaboration.CaretLabels>maxcollapses extra avatars into a+Nchip. An avatar renderer receivesparticipant,color,initials, andavatarUrl.DocxEditorCollaboration.Avatarrenders one participant.participanthasactorId,name, optionalcolor, optionalrole, andisLocal.- Label renderers can use editor and review hooks. The label layer is
aria-hiddenand ignores pointer events, so put interactive controls in your own chrome. - CSS hooks: the
docx-remote-caret-labelclass,--doc-remote-colorproperty, anddata-docx-remote-actorattribute. <DocxEditor.AuthorStyle author="Alex Kim" color="#1f7a4d" avatarUrl="/team/alex.jpg" />sets one picture and color for avatars, caret labels, and review cards. It matches thew:authordisplay name and outranks a peer'sidentity.color. See Review styling.
Recover a diverged replica
A status of error pauses editing, and the replica keeps its last good document. Choose the action by failure code:
| Failure | Action |
|---|---|
Healing codes, such as remote-apply-failed, while recovering is true | Wait. A later update restores the earlier status. |
collaboration-format-mismatch, protocol-version-mismatch, schema-version-mismatch | Preserve local work and follow collaboration upgrades. Rejoining cannot fix these. |
authentication-failed | Refresh the credential, then rejoin. |
room-generation-changed | Preserve a copy, then rejoin. Edits made while away are not in the new room. |
concurrent-seed, blob-digest-mismatch, resource limits | Save a copy and create a new room from it. |
transport-disconnected while ready on WebRTC | None. One peer link cannot carry large updates; other peers still receive each edit. |
Preserve a copy before you rejoin:
const saved = await editorRef.current?.save(); // Empty when no document is open.
if (saved) {
const bytes = new Uint8Array(saved);
await preserveRecoveryCopy(bytes); // Stop recovery if this rejects.
const failure = await rejoin(bytes); // Resolves, never rejects.
if (failure) showRecoveryMessage(failure.code);
}rejoin joins with { kind: 'join' }, and the room copy wins. It does not merge your saved bytes, so unreplicated changes can be lost. After a failed join, the saved bytes stay mounted.
While a room is live, it is the document. An export is a read-only snapshot that cannot merge back. Apply outside edits inside the room, or start a new room from the edited file.
Edit offline
The session accepts edits while disconnected and merges them after reconnection. offlineEditing: false refuses them instead. The session always refuses edits in error.
unsyncedChanges counts unconfirmed edits. On Hocuspocus, the server has not confirmed them. On WebRTC, they were made while no peer was connected, and exist only in your browser. Warn before the page closes:
useEffect(() => {
if (unsyncedChanges === 0) return;
const warn = (event: BeforeUnloadEvent) => event.preventDefault();
window.addEventListener('beforeunload', warn);
return () => window.removeEventListener('beforeunload', warn);
}, [unsyncedChanges]);Buffered edits live in memory, and a reload, unmount, or room change drops them. To keep them, persist the Yjs document, for example with y-indexeddb. A zero count does not confirm durable server storage.
Prepare the room document on a server
If your server holds a Y.Doc per room, as Hocuspocus does, call prepareCollaborationServerDocument before it applies any update, saved state included. Otherwise Yjs removes formatting markers it finds redundant and sends that change to every participant:
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { Server } from '@hocuspocus/server';
import * as Y from 'yjs';
import {
assertCollaborationFormatCompatibility,
checkCollaborationRoomGeneration,
prepareCollaborationServerDocument,
readCollaborationDocument,
readCollaborationFormatVersion,
} from '@docx-editor.dev/pro/collaboration';
// No `.`, `/`, or `\`, so a room name cannot leave the directory.
const ROOM_ID = /^[A-Za-z0-9_-]{24,256}$/;
function roomFile(documentName: string): string {
if (!ROOM_ID.test(documentName)) throw new Error('unknown room');
return path.join('/var/lib/rooms', `${documentName}.ydoc`);
}
async function readSavedRoom(file: string): Promise<Uint8Array | null> {
try {
return new Uint8Array(await readFile(file));
} catch (error) {
// Only ENOENT means no saved room. Other storage errors stop the load.
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
throw error;
}
}
const server = new Server({
async onLoadDocument({ documentName, document }) {
prepareCollaborationServerDocument(document);
const saved = await readSavedRoom(roomFile(documentName));
if (saved) {
const candidate = new Y.Doc(); // Validate before loading.
try {
prepareCollaborationServerDocument(candidate);
Y.applyUpdate(candidate, saved);
assertCollaborationFormatCompatibility(readCollaborationFormatVersion(candidate));
readCollaborationDocument(candidate);
Y.applyUpdate(document, saved);
} finally {
candidate.destroy();
}
}
return document;
},
async afterLoadDocument({ document }) {
document.flush(); // Send the loaded state to nobody before the first join.
},
async beforeHandleMessage(payload) {
checkCollaborationRoomGeneration(payload);
},
});documentNameis untrusted client input. In production, check room access inonAuthenticateand add client admission checks.- Preparation does not validate or authenticate. Validation failures stop the load and keep the saved state.
- Hocuspocus 4.6 holds back updates smaller than
flushMaxBytes. Withoutdocument.flush(), the first participant receives the loaded state twice. - A relay-only server with no
Y.Docneeds no preparation. - Extension hooks run before the server's hooks. If an extension such as
@hocuspocus/extension-databaseloads state, callprepareCollaborationServerDocumentin your own extension'sonLoadDocumentwithpriority: 1000(default 100), listed first.
Seed new rooms on a server
A participant that seeds a Hocuspocus room uploads the whole state, and the server echoes it back. If your server knows a room's document, seed it with createCollaborationState instead:
import * as Y from 'yjs';
import {
CollaborationSchemaError,
createCollaborationState,
prepareCollaborationServerDocument,
} from '@docx-editor.dev/pro/collaboration';
declare const storage: {
readState(room: string): Promise<Uint8Array | null>;
readDocx(room: string): Promise<Uint8Array | null>;
hasSeedRecord(room: string): Promise<boolean>;
writeSeedRecord(room: string): Promise<void>; // Kept apart from the state.
writeStateIfAbsent(room: string, state: Uint8Array): Promise<boolean>; // Create-only.
};
/** Hocuspocus sends `reason` to the refused client. */
const refusal = (reason: string) => Object.assign(new Error(reason), { reason });
async function onLoadDocument({ documentName: room, document }) {
prepareCollaborationServerDocument(document);
let state = await storage.readState(room);
if (!state) {
// A known room lost its state. Never seed it again.
if (await storage.hasSeedRecord(room)) throw refusal('saved-room-unavailable');
const docx = await storage.readDocx(room);
if (!docx) throw refusal('unknown-room');
try {
state = await createCollaborationState(docx, { documentId: room, maxBytes: 4 * 1024 * 1024 });
} catch (error) {
throw refusal(error instanceof CollaborationSchemaError ? error.code : 'invalid-baseline');
}
// Hocuspocus does not store state applied during load. Another process may win.
if (!(await storage.writeStateIfAbsent(room, state))) state = await storage.readState(room);
if (!state) throw refusal('saved-room-unavailable');
}
// Also repairs a crash between the state write and the record write.
if (!(await storage.hasSeedRecord(room))) await storage.writeSeedRecord(room);
Y.applyUpdate(document, state);
return document;
}Keep the afterLoadDocument and beforeHandleMessage hooks from the previous section, and store state in onStoreDocument. For a complete file-based server, see server/server.ts in the Hocuspocus example.
- Seed only a room your application knows is new. A second seed replaces the room with the original file, and every later edit is lost.
- Refuse a known room without state with
saved-room-unavailable. Participants keep their copies while you restore it. - Write new state create-only, so two processes loading one new room keep one seed.
- Store the seed record apart from the state, for example in a database.
- Each seed carries a new room generation. If you lose state and record and seed again,
checkCollaborationRoomGenerationrefuses old replicas withroom-generation-changed. - With
@hocuspocus/extension-database, seed infetchwith a create-only insert such asINSERT ... ON CONFLICT DO NOTHING, then read the row back. Hocuspocus does not callstorefor state thatfetchreturns.
Plan for the cost of a seed
createCollaborationState is mostly synchronous. On a laptop, 10,000 paragraphs (4.4 MiB of XML) took 5.2 seconds, with blocks of up to 210 ms. 30,000 paragraphs took 26 seconds and 3 GiB.
- Set
maxBytesto your largest accepted document. It bounds the file and its expanded package. Default and maximum: 20 MiB. - Seed in a worker thread or a low-concurrency job queue, ideally when the application creates the room.
- It throws
CollaborationSchemaErrorwithbaseline-too-large(before parsing),invalid-baseline, orinvalid-document-id. AmaxBytesthat is not a whole number from 1 to 20 MiB throwsTypeError.
Compact rooms on a server
Yjs state only grows. Compact a room into a new generation when the server loads it, before anyone syncs:
async onLoadDocument({ documentName, document }) {
prepareCollaborationServerDocument(document);
const file = roomFile(documentName);
const saved = await readSavedRoom(file);
if (!saved) return document;
// Throws on validation failure. The stored state stays unchanged.
const compacted = await compactCollaborationState(saved);
if (compacted) await writeReplacing(file, compacted); // Temporary file + rename.
Y.applyUpdate(document, compacted ?? new Uint8Array(saved));
return document;
},roomFile and readSavedRoom come from Prepare the room document on a server. Keep the afterLoadDocument and beforeHandleMessage hooks.
compactCollaborationStatereturnsnullwhen the stored state is less than twice a fresh build of the content.- It throws
CollaborationSchemaErrorfor an invalid room, and other errors for invalid Yjs bytes. Stop the load, keep the stored state, and investigate before admitting clients. - It caches up to 1,024 states that need no compaction per process. Other states get a full check.
- Every Hocuspocus server that holds rooms must call
checkCollaborationRoomGenerationinbeforeHandleMessage, to refuse earlier-generation replicas before they merge. - The new generation keeps the document, comments, and tracked changes, but not undo history.
- A replica that stayed open across compaction gets
room-generation-changed. Recover it as Recover a diverged replica shows. readCollaborationRoomGeneration(ydoc)returns the generation, or an empty string for a participant-seeded, never-compacted room.
Read a room from a server
readCollaborationDocument(ydoc) returns the room as .docx bytes. Call it from Hocuspocus onStoreDocument for export, autosave, or indexing:
await writeFile(`${roomFile(documentName)}.docx`, readCollaborationDocument(document));It joins nothing and does not write. An unseeded or unsynced Y.Doc throws not-initialized. It also throws CollaborationSchemaError for concurrent-seed, blob-digest-mismatch, materialization, and resource-limit failures. Keep the last valid export.
Integrate a custom Yjs provider
If you own a Y.Doc and awareness instance, call createDocumentCollaboration from @docx-editor.dev/pro/collaboration, and destroy the resources yourself.
Implement transport admission first. Before any update applies, authenticate access, compare the complete collaboration format, and check the room generation. Repeat on reconnection. checkCollaborationRoomGeneration reads only Hocuspocus messages, so a custom transport needs its own generation handshake. For format checks, see Collaboration versions and upgrades.
The following example wires y-websocket. It disables cross-tab broadcasts, which bypass admission:
import * as Y from 'yjs';
import { Awareness } from 'y-protocols/awareness';
import { WebsocketProvider } from 'y-websocket';
import {
createDocumentCollaboration,
prepareCollaborationServerDocument,
} from '@docx-editor.dev/pro/collaboration';
// Resolves on the provider's first `sync` event. Rejects after a timeout.
declare function waitForSync(provider: WebsocketProvider): Promise<void>;
async function openRoom(name: string) {
const ydoc = new Y.Doc();
// Preserve formatting markers while the provider receives initial updates.
const stopPreparation = prepareCollaborationServerDocument(ydoc);
const awareness = new Awareness(ydoc);
const provider = new WebsocketProvider('wss://example.test', 'room-1', ydoc, {
awareness,
disableBc: true,
});
const destroyResources = () => {
provider.destroy();
awareness.destroy();
stopPreparation();
ydoc.destroy();
};
try {
await waitForSync(provider);
const room = await createDocumentCollaboration({
ydoc,
awareness,
documentId: 'room-1',
identity: { actorId: crypto.randomUUID(), name }, // Unique per editor.
bootstrap: { kind: 'join' },
});
const onStatus = ({ status }: { status: string }) =>
status === 'connected'
? room.session.setTransportStatus('ready')
: room.session.setTransportStatus('disconnected', 'transport-disconnected');
provider.on('status', onStatus);
onStatus({ status: provider.wsconnected ? 'connected' : 'disconnected' });
return {
room, // Mount the editor with room.document and its collaboration module.
destroy() {
provider.off('status', onStatus);
room.destroy();
destroyResources();
},
};
} catch (error) {
destroyResources();
throw error;
}
}- Sync the provider before
bootstrap: { kind: 'join' }, or the join fails withinitialization-timeoutafter 30 seconds. - Pass an
Awarenessfromy-protocols/awarenessfor presence. - Send connection events to
session.setTransportStatus, or the status staysreadyduring an outage. The second argument is aCollaborationFailureCode; the third holds diagnostic text. - Report rejected credentials as
errorwithauthentication-failed, becausedisconnectedstill permits offline editing.
The factory rejects with CollaborationSchemaError; see Failure codes. Custom ports and direct store integrations must call room.session.gateOperations(ops, scope) before committing edits, and stop on an error code.
To recover from a terminal error, save the document, call room.destroy(), and destroy your resources. Create and connect new ones, then call createDocumentCollaboration with bootstrap: { kind: 'join' }. Keep the editor mounted with the saved bytes until the room is ready; rejoining does not merge them. Never change version metadata to bypass a format check.
To implement replication, import CollaborationDocumentPort and CanonicalPrimitiveJournal from @docx-editor.dev/core/collaboration/replication. If the port's host shows undo state to a person, set interactive: true. The session then refuses beginUndoGroup() with editor-attached, and closes an open group when the port attaches.
Create a headless replica
DocxEditor.createCollaborative from @docx-editor.dev/editor-api opens a DOM-free replica over a synced room:
import { DocxEditor } from '@docx-editor.dev/editor-api';
import { createDocumentCollaboration } from '@docx-editor.dev/pro/collaboration';
const room = await createDocumentCollaboration({
ydoc, // Prepared and synced, as in the custom provider example.
awareness,
documentId: 'room-1',
identity: { actorId: crypto.randomUUID(), name: 'Agent', role: 'agent' },
bootstrap: { kind: 'join' },
});
const runtime = await DocxEditor.createCollaborative(room.document, room.session, {
author: 'Agent',
});context.sync() commits to the local replica only. It does not confirm delivery or durable storage, so wait for the provider to acknowledge outgoing updates. In finally, call runtime.dispose(), room.destroy(), and then destroy resources you created.
Let a server agent propose redlines
A background worker joins the Hocuspocus room with role: 'agent' through a headless replica. Closing the browser does not stop it. Set the tracking mode, then use ordinary edits:
await runtime.run(async (context) => {
const matches = context.document.body.search('within 7 days', { matchCase: true });
matches.load('items');
await context.sync();
if (matches.items.length !== 1) throw new Error('Choose a unique target');
const range = matches.items[0]!;
range.load('text');
await context.sync();
// Decide from the loaded snapshot; sync refuses if the replica changed meanwhile.
context.document.changeTrackingMode = 'TrackMineOnly';
range.insertText('within 30 days', 'Replace');
await context.sync();
});- Configure
authoron the runtime.TrackMineOnlypersists across runs and does not change other participants' modes.Offmakes permanent edits.TrackAllfails withNotSupported. - Tracked replacements stay within one paragraph.
range.delete()andparagraph.delete()can propose paragraph deletions. - Unsupported boundaries and structural edits refuse the entire sync. See supported tracked edits.
- Commit one logical suggestion per sync. On a stale snapshot, reread and reconsider; never replay.
- The stale check sees only changes that reached the worker. It cannot detect remote edits still in transit.
- Browser peers need the Pro review module to show suggestions.
For a full worker with persistence, cancellation, transport acknowledgement, and cleanup, see the server agent review example.
Undo an agent operation
Each session has its own undo history. Without a group, writes under 500 milliseconds (ms) apart merge into one step. To make one operation one step, open an undo group:
const group = room.session.beginUndoGroup();
try {
await runtime.run(async (context) => {
context.document.body.insertParagraph('Summary of changes', 'End');
await context.sync();
});
} finally {
group.end(); // After `runtime.run()` resolves, not inside the callback.
}
room.session.undo(); // Later: revert the operation, keep others' edits.- Every published local write joins the open group. The first write after
group.end()starts a new step. - While a group is open,
undo(),redo(),canUndo(), andcanRedo()returnfalse, andsession.undoGroupOpenistrue. - A refused write does not end the group.
group.end()is safe to call twice.room.destroy()closes an open group. - Undo keeps others' edits. If others removed all the group wrote, undo changes nothing and never reverts an older step. Undo of an ungrouped step never reverts a group below it.
- If others removed all an ungrouped step wrote,
undo()changes nothing and returnstrue. The nextundo()reverts the preceding group. - Groups do not nest. Give each concurrent operation its own session.
- Sessions with an attached editor refuse groups; use
editor.beginHistoryGroup()there. A collaborative server runtime refusesruntime.run({ historyGroup })withNotSupported.
beginUndoGroup() throws CollaborationUndoGroupError:
| Code | Cause | Action |
|---|---|---|
undo-group-already-open | The session has an open group. | End it, or use another session. |
editor-attached | An editor is attached. | Use editor.beginHistoryGroup(), or a separate agent session. |
collaboration-session-destroyed | The session was destroyed. | Join with a new session. |
Collaboration behavior and limits
- A WebRTC room exists while one peer stays connected.
- One process or page can host many rooms, each with its own Yjs document, undo, and carets. Give each document its own room name, and each room its own awareness instance. On Hocuspocus, check the tenant of
documentNameinonAuthenticate. - Replicas synchronize comments, tracked-change decisions, tables of contents, and custom nodes through named review actions. They reject an edited ProseMirror document and review writes without a named intent.
- Edits are refused when the session is destroyed, not ready, or not attached. An outage pauses editing only with
offlineEditing: false. - Collaboration undo follows the typing and undo rules and keeps other participants' edits.
- An incomplete update pauses edits only in affected paragraphs, with
collaboration-session-not-ready. - Participants converge on one document, and carets stay beside the same characters. Two concurrent cases can surprise users:
- Formatting applied while another participant moves that text to another paragraph can be lost.
- A split, a concurrent join, and a third participant's typing can place the typed text earlier than expected. It appears once everywhere.
| Concurrent edits | Result |
|---|---|
| You delete text while another participant moves it. | The text stays deleted. You can undo the deletion. |
| You delete an image while another participant changes it. | The deletion wins. |
| Two participants paste paragraphs at the same position. | Both pastes and the surrounding text stay. |
| Two participants insert pictures, from the editor or the document API. | Both pictures stay. |
| You delete a paragraph while another participant inserts a picture in it. | The deletion wins. The media part and its relationship stay in the package. |
Numeric limits
| Limit | Value | Failure code | Remedy |
|---|---|---|---|
| Seed document, compressed and uncompressed | 20 MiB, or a lower maxBytes | baseline-too-large | Reduce the document. |
| Files in the seed document | 10,000 | invalid-baseline | Remove parts. |
| One embedded file | 32 MiB | blob-too-large | Compress the media. |
| All embedded files | 64 MiB | blob-store-full | Remove media; create a new room. |
| Document nodes, deleted included | 200,000 | too-many-nodes | Export; create a new room. |
| Nesting depth | 256 levels | tree-too-deep | Flatten nested tables or content controls. |
| Children of one node | 100,000 | too-many-children | Split the content. |
| Attributes of one element | 4,096 | too-many-attributes | Reduce the document. |
| Package parts | 512 | too-many-parts | Remove parts; create a new room. |
| Relationships | 10,000 | too-many-relationships | Remove links or media; create a new room. |
| Text in one paragraph | 1,048,576 characters | text-too-long | Split the paragraph. |
| One inserted text | 1,048,576 characters | collaboration-text-limit | Insert smaller pieces. The session stays ready. |
actorId, name, documentId, sessionId | 256 characters | invalid-identity, invalid-document-id, invalid-session-id | Shorten the value. |
Identity color | 64 characters | invalid-identity-color | Shorten the value. |
| Presence participants | 256 | None | Reads return the first 256. |
| Initial synchronization | 30 seconds | initialization-timeout | Connect the provider. On Hocuspocus, raise syncedTimeoutMs. |
Watch a room's size
A room grows between compactions, and crossing a limit ends it. A WebRTC room has no server to compact it. Subscribe to resource pressure to warn users early:
const stop = session.subscribeResourcePressure(
({ limit, fraction, threshold }) => {
if (threshold === 0) hideRoomSizeWarning();
else showRoomSizeWarning(limit, fraction); // Suggest a new room from saved bytes.
},
{ thresholds: [0.75, 0.9] } // The default.
);- The listener runs on each threshold crossing, and once at subscription if a threshold is already reached.
limitisnodes,parts,relationships, orblobBytes. session.resourceUsage()returns each count beside its limit, such asnodesandmaxNodes. On a server,readCollaborationResourceUsage(ydoc)reads a syncedY.Docwithout joining or writing.- Both probes walk the node map. Read them on a schedule, not on every edit.
formattingMarkerscounts the formatting markers in paragraph text. Deleting the formatted text does not remove them; compaction does.- When a limit ends the room,
detailnames it, such asnodes=200001.
Failure codes
Every failure carries a CollaborationFailureCode. Sessions report it in statusSnapshot().reason; factories and server helpers throw it as CollaborationSchemaError.code. Branch on the code and log detail.
Recovery types: Refused edit (status unchanged), Thrown (no session exists), Heals (error until a later update completes the state), and Terminal (error stays).
| Code | Cause | Recovery | Action |
|---|---|---|---|
collaboration-session-not-ready | Status is initializing, error, or disconnected with offlineEditing: false, or an update waits for a dependency. | Refused edit | Wait for ready. |
collaboration-session-not-attached | No editor attached its port. | Refused edit | Remount with the room's modules. |
collaboration-session-destroyed | The session was destroyed. | Refused edit | Mount a new session. |
collaboration-text-limit | One insert exceeds the shared text limit. | Refused edit | Insert smaller pieces. |
experimental-collaboration-body-text-only | A review write has no named intent. | Refused edit | Use a named review command. |
invalid-document-id, invalid-session-id, invalid-identity, invalid-identity-color | An option is empty or too long. setIdentity also throws identity codes. | Thrown | Fix the value. |
already-initialized | A create bootstrap found a seeded room. | Thrown | Use join or create-or-join. |
document-id-mismatch | The room, or an attached editor, has another documentId. | Thrown or terminal | Check both IDs. |
initialization-timeout | No synced room appeared in time. | Thrown | Connect the provider or raise the timeout. |
initialization-aborted | The signal aborted, or the server refused the credential during the join. | Thrown | Refresh the credential and connect again. |
not-initialized | A server helper read an unseeded room. | Thrown | Wait for sync. Create a room only if storage confirms none exists. |
baseline-too-large, invalid-baseline, no-main-document-part, blob-read, missing-local-blob | The seed bytes cannot open as a document. | Thrown | Fix or reduce the file. |
collaboration-format-mismatch, protocol-version-mismatch, schema-version-mismatch | Client and room formats differ. | Thrown or terminal | Save local work. Use a compatible deployment, or upgrade the saved room. |
concurrent-seed | Two peers seeded the room at once. | Thrown or terminal | Save local work; create a new room from it. |
blob-digest-mismatch | An embedded file does not match its digest. | Thrown or terminal | Save local work; create a new room from it. |
port-already-attached | A second editor attached to one session. | Terminal | Give each editor its own session. |
remote-apply-failed, materialize-dropped-content, missing-blob, missing-root, invalid-relationships | A peer's update is incomplete, or a joined room forms no document. | Heals; thrown during join | Wait. If it persists, save and rejoin. |
duplicate-paragraph-id, unknown-paragraph-id | A custom integration sent a paragraph update the port cannot apply. | Port result | Update only paragraphs the port lists. |
text-too-long, too-many-nodes, too-many-children, too-many-attributes, too-many-parts, too-many-relationships, tree-too-deep, blob-too-large, blob-store-full | A document or edit crosses a numeric limit. | Thrown, heals, or terminal | A refused local edit realigns. For shared state, create a new room. |
invalid-blob-descriptor, invalid-bound, invalid-logical-id, invalid-string, prototype-key, unknown-logical-id, unsafe-part-name | Shared state or an edit fails a trust-boundary check. | Thrown, heals, or terminal | Treat the room as untrusted. If it persists, use a new room. |
transport-disconnected | The connection dropped, or one WebRTC peer link cannot carry large updates. | Recovers | Wait and show the status. |
authentication-failed | The server rejected the credential after the join. | Terminal | Refresh the credential, then rejoin. |
room-generation-changed | The server compacted or reseeded the room while this replica was away. | Terminal | Save unsent edits, then rejoin. |
transport | A hook could not connect, and the provider gave no recognized code. | Hook error | Fix the options and retry. |
invalid-saved-room, saved-room-unavailable | Your server refused to load a saved room. | Terminal | Repair the server's storage. |
Deprecated codes that nothing emits: baseline-digest-mismatch, experimental-collaboration-existing-paragraphs-only, experimental-collaboration-text-only, experimental-collaboration-untracked-text-only, immutable-baseline-changed, immutable-metadata-changed, invalid-shared-metadata, local-mirror-failed, paragraph-set-mismatch, shared-schema-invalid, and unsupported-root-key.