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. On a Hocuspocus server, collaborationServerExtension does both. For other servers, 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 # Hocuspocus

yjs, y-webrtc, and @hocuspocus/provider are optional Pro peer dependencies. Pro installs y-protocols.

EntryExports
@docx-editor.dev/pro/{react,vue}/webrtcuseWebrtcCollaboration. A subpath keeps the provider out of other bundles.
@docx-editor.dev/pro/{react,vue}/hocuspocususeHocuspocusCollaboration
@docx-editor.dev/pro/{react,vue}DocxEditorCollaborationRoot, DocxEditorCollaboration, useCollaborationStatus, useCollaborationParticipants, useDocumentCollaboration, and the CollaborationSession, CollaborationStatus, and CollaborationFailure types
@docx-editor.dev/procollaborationModule, without a network provider
@docx-editor.dev/pro/collaborationYjs factories and server helpers
@docx-editor.dev/pro/collaboration/webrtccreateWebrtcCollaboration, DEMO_SIGNALING_ENDPOINTS, createCollaborationRoomId
@docx-editor.dev/pro/collaboration/hocuspocuscreateHocuspocusCollaboration

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 })).

FieldDescription
documentRoom bytes. null until the room joins.
modulesYour modules plus collaborationModule. Pass them to the editor.
sessionCollaborationSession with identity, status, presence, and undo. No attach or gateOperations.
errorCollaborationFailure 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, providernull before the first connection. For persistence or direct provider access.
unsyncedChangesEdits that have not reached the room. See Edit offline.
  • Give each peer a unique actorId, including each tab of one user.
  • Set key to session?.sessionId. The editor reads modules only at construction, so without key, edits do not replicate.
  • Pass review and custom-node modules through the hook's modules option. A second collaboration module throws.
  • Branch on error.code, never on message text. Handle error even when document is set.
  • Omit room to connect later with connect. That room stays open until leave.
  • Changing the room, server, bootstrap kind, or actorId in room reconnects; room: null leaves. Save local work first.

Choose a bootstrap

bootstrap.kindBehavior
create-or-joinThe first peer seeds the empty room from document. Later peers join. Every peer uses the same settings.
createSeeds the room. On Hocuspocus, it waits for server state, then fails with already-initialized if the room is seeded, or initialization-timeout after syncedTimeoutMs.
joinJoins 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 valueResult
Your ws:// or wss:// URLsProduction setup.
DEMO_SIGNALING_ENDPOINTSShared, 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 invalidNo 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.

OptionDescription
urlHocuspocus server URL. The provider adds the collaborationFormat query parameter, which names the client's collaboration format, and removes trailing slashes from the path.
tokenString, 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.
syncedTimeoutMsInitial sync limit. Default 30 seconds. Fails with initialization-timeout.
bootstrap.signalCovers the whole join, including the server's room load. Fails with initialization-aborted.
offlineEditingfalse 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-aborted during the join, or authentication-failed after it, with the reason in detail.
  • createHocuspocusCollaboration takes the same options and returns the room, ydoc, and provider.
  • The Hocuspocus v4 server runs on Node, not Bun. Use @hocuspocus/provider for 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>
  );
}
  • The root renders fallback while document is null. In Vue, it renders nothing without the slot.
  • Show error beside 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 session argument.
  • 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:

FieldDescription
statusSession state, or inactive without a session.
reasonCause of the present state, such as a failing WebRTC link while ready. Clears after recovery.
lastFailureLatest error failure. Not set by a ready or disconnected reason.
liveEdits made now reach the room.
divergeddestroyed, or an error that does not heal. Offer rejoin.
recoveringerror that the next update heals. Show a short notice, not a rejoin action.
waitingEdits wait for an update they depend on. The editor refuses edits until it arrives.
failureCountNumber of recorded failures. Changes on each failure, even with the same code.
attachedAn 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} />;
StateRejoin button
Connecting, offline, or catching up on an updateNo
Edits wait for the latest room changesAfter 10 seconds
The room refused an edit, and the editor undid itNo
Out of syncYes, if you handle rejoin
Upgrade required: client and room formats differNo
New room required: merged seeds, a damaged stored file, or a resource limitNo

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>
  • max collapses extra avatars into a +N chip. An avatar renderer receives participant, color, initials, and avatarUrl. DocxEditorCollaboration.Avatar renders one participant.
  • participant has actorId, name, optional color, optional role, and isLocal.
  • Label renderers can use editor and review hooks. The label layer is aria-hidden and ignores pointer events, so put interactive controls in your own chrome.
  • CSS hooks: the docx-remote-caret-label class, --doc-remote-color property, and data-docx-remote-actor attribute.
  • <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 the w:author display name and outranks a peer's identity.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:

FailureAction
Healing codes, such as remote-apply-failed, while recovering is trueWait. A later update restores the earlier status.
collaboration-format-mismatch, protocol-version-mismatch, schema-version-mismatchPreserve local work and follow collaboration upgrades. Rejoining cannot fix these.
authentication-failedRefresh the credential, then rejoin.
room-generation-changedPreserve a copy, then rejoin. Edits made while away are not in the new room.
concurrent-seed, blob-digest-mismatch, resource limitsSave a copy and create a new room from it.
transport-disconnected while ready on WebRTCNone. 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.

Run a room server

collaborationServerExtension is a Hocuspocus extension that does the room's part of a server. Add it to extensions, and write only authentication and storage. For a short path through setup, adoption, and format upgrades, see the Hocuspocus room server guide.

import { Server } from '@hocuspocus/server';
import {
  collaborationServerExtension,
  type CollaborationRoomStorage,
} from '@docx-editor.dev/pro/collaboration';

// Implement these with your database and your access-token service.
interface RoomRow {
  state: Uint8Array;
  docx: Uint8Array | null;
  digest: string | null;
}
declare const rooms: {
  read(roomName: string): Promise<RoomRow | null>;
  writeState(roomName: string, state: Uint8Array): Promise<void>;
  writeExport(roomName: string, docx: Uint8Array, digest: string): Promise<void>;
};
declare function verifyDocumentAccess(token: string, roomName: string): Promise<void>;

const storage: CollaborationRoomStorage = {
  async load(roomName) {
    const room = await rooms.read(roomName);
    if (!room) return null;
    const exported =
      room.docx && room.digest ? { docx: room.docx, stateDigest: room.digest } : null;
    return { state: room.state, export: exported };
  },
  async save(roomName, room) {
    // Write the state first, or both in one transaction.
    await rooms.writeState(roomName, room.state);
    // `export` is null when this store has no new export. Keep the export you already store.
    if (room.export) {
      await rooms.writeExport(roomName, room.export.docx, room.export.stateDigest);
    }
  },
};

const server = new Server({
  port: 1234,
  async onAuthenticate({ token, documentName }) {
    await verifyDocumentAccess(token, documentName);
  },
  extensions: [collaborationServerExtension({ storage })],
});

The extension runs before your other extensions and your own hooks. It does the following:

  • Checks the client's format. It refuses a client of another collaboration format with collaboration-format-mismatch, before synchronization. The provider hooks and createHocuspocusCollaboration send the format in the collaborationFormat query parameter of the server URL.
  • Prepares the room document before any update reaches it, and flushes the loaded room so that the first participant receives it once.
  • Refuses earlier-generation replicas before their state merges.
  • Checks each stored room before it becomes the live room. The room must be in the server's format and must export as a complete document.
  • Stores each room with an export. Each store writes the room state, a DOCX export, and the SHA-256 of the exported state. A load adds a missing export and replaces a stale one.
  • Upgrades a stored room of an earlier format from its export when the server loads it. See Rooms upgrade when the server loads them.

Pass these options to collaborationServerExtension:

OptionDefaultEffect
storageNoneLoads, checks, and stores rooms. Without it, the extension checks clients, prepares the room document, and refuses replicas of an earlier room generation. Load and store in your own hooks.
createRoomNoneReturns the state of a room that storage does not hold, such as the result of createCollaborationState. The extension stores it before anyone synchronizes.
upgradeOnLoadtruefalse refuses a stored room of an earlier format.
maxUpgradeStateBytes64 MiBThe largest stored state that the server upgrades on load. A larger room is refused. Upgrade it in a job.
compactOnLoadfalseCompacts a stored room on load, as Compact rooms on a server describes. Accepts the same options.
exportIntervalMs0The shortest time between two exports of one room while people are connected. 0 exports on each store.
readClientFormatQuery parameterReads the client's format from another place, such as your token.
onEventNoneReceives room events. See Log room events.
  • documentName is untrusted client input. Check room access in onAuthenticate, and validate the name before it reaches a file path or a query.
  • Do not load or store rooms in your own hooks when you pass storage.
  • Clients of a release that does not send the collaborationFormat parameter are refused. Update the clients first, or see Admit earlier clients during a rollout.
  • A room that does not export as a document is not stored, because a load refuses such a state. Storage keeps the last room that exported, and onEvent receives room-export-failed.
  • If save throws, Hocuspocus logs the error and does not try that store again. The extension stores the room again before the room unloads, and an error then keeps the room in memory.
  • Store each export with the digest that arrives with it. The digest is the only link between an export and a state, and the server never uses an export of another state.
  • An export and an upgrade run on the server's thread, and every room on the process waits. See Plan for the cost of exports and upgrades.
  • With exportIntervalMs above 0, a store inside the interval writes a state that the server did not check, and leaves a stale export. A room always exports before it unloads. If the server stops before that, the next load with the same release replaces the export. A load after a format change refuses the room. If an unchecked state does not export, each later load refuses it with invalid-saved-room, and the stored export holds the last document that exported.
  • One server process must hold a room at a time. If two servers load one earlier-format room at the same time, each creates its own room, and the later store replaces the other.
  • A custom provider has no extension. Run the same checks in its admission flow, as Integrate a custom Yjs provider describes.

For a complete server with file storage, room creation, and telemetry, see the Hocuspocus server example.

Create rooms from your documents

Without createRoom, a room that storage does not hold stays empty, and its first participant seeds it. To create each room from a document that your application holds, return its state from createRoom:

import {
  collaborationServerExtension,
  createCollaborationState,
  type CollaborationRoomStorage,
} from '@docx-editor.dev/pro/collaboration';

declare const storage: CollaborationRoomStorage;
// Your document store. `null` means that the application has no such document.
declare function readDocx(roomName: string): Promise<Uint8Array | null>;

export const rooms = collaborationServerExtension({
  storage,
  async createRoom({ roomName }) {
    const docx = await readDocx(roomName);
    // Hocuspocus sends `reason` to the refused client.
    if (!docx) throw Object.assign(new Error('unknown-room'), { reason: 'unknown-room' });
    return createCollaborationState(docx, { documentId: roomName });
  },
});
  • The extension checks the state, stores it with an export, and then loads it. Clients join with bootstrap: { kind: 'join' }.
  • createRoom runs only when storage.load returns null. If a known room can lose its state, throw from load and do not return null, or the room is created again from the original document.
  • context in the request is the value that your onAuthenticate returned for the connection.
  • For the cost of createCollaborationState, see Plan for the cost of a seed.

Keep the earlier state of an upgraded room

Add backUp to your storage. The extension calls it with the earlier state before it stores an upgraded room:

import type { CollaborationRoomStorage } from '@docx-editor.dev/pro/collaboration';

declare const base: CollaborationRoomStorage;
declare const backups: { write(key: string, bytes: Uint8Array): Promise<void> };

export const storage: CollaborationRoomStorage = {
  ...base,
  async backUp(roomName, state) {
    await backups.write(`${roomName}/${new Date().toISOString()}.ydoc`, state);
  },
};

An error from backUp stops the upgrade, and the stored room stays as it is. Only the release that wrote a backup can read it. To use one, follow Roll back a migration.

Log room events

onEvent receives one object for each thing the extension does to a room. Send the events to your log, and count them by type and reason:

import {
  collaborationServerExtension,
  type CollaborationRoomStorage,
  type CollaborationServerEvent,
} from '@docx-editor.dev/pro/collaboration';

declare const storage: CollaborationRoomStorage;
declare const metrics: { count(name: string, labels: Record<string, string>): void };

function onEvent(event: CollaborationServerEvent): void {
  const reason = event.type === 'room-upgrade-refused' ? event.reason : '';
  metrics.count('collaboration_room_events', { type: event.type, reason });
  // Events hold codes, part names, and positions. They never hold document text.
  console.log(JSON.stringify(event));
}

export const rooms = collaborationServerExtension({ storage, onEvent });
Event typeMeaningAction
room-upgradedThe server upgraded a stored room to its format. hidden counts paragraphs that the editor cannot show.None, when hidden is 0.
room-upgrade-refusedThe server did not upgrade a room of an earlier format. reason says why. Clients get saved-room-unavailable.Migrate the room in a job. See the reasons.
room-load-refusedThe stored room is of a later format, or it forms no document. code says which.Serve the room with the release that wrote it, or restore it.
room-export-failedThe room does not export as a document, so the server did not store it.Check code. Storage keeps the last room that exported.
room-compaction-failedA compaction on load failed. The room loaded as it was stored.Check code.

An error that onEvent throws is ignored.

Admit earlier clients during a rollout

The extension refuses a client that sends no collaborationFormat parameter. Clients of a release that does not have the extension send none. To add the extension while such clients are still open, admit a missing value for one release:

import {
  COLLABORATION_FORMAT_PARAMETER,
  COLLABORATION_FORMAT_VERSION,
  collaborationServerExtension,
} from '@docx-editor.dev/pro/collaboration';

export const rooms = collaborationServerExtension({
  // A client that names a format is still checked. Remove this when all clients send one.
  readClientFormat: ({ requestParameters }) =>
    requestParameters.get(COLLABORATION_FORMAT_PARAMETER) ?? COLLABORATION_FORMAT_VERSION,
});

Use this only between releases of one collaboration format. A client of another format that sends no parameter then synchronizes, and its room fails.

Plan for the cost of exports and upgrades

The extension exports the room on each load and each store, and an upgrade creates the room again. This work runs on the server's thread, so every room on that process waits. A room state is much larger than its DOCX file. These values are from one laptop:

DocumentDOCX sizeRoom stateLoad checkExport on a storeUpgrade on load
Sample document75 KB4.2 MiB0.26 s0.16 s0.53 s
Document of 1.1 MB1.1 MB2.2 MiB0.42 s0.37 s1.4 s
Document with many tracked changes86 KB11 MiB2.1 s1.9 s7.9 s
Document of 521 pages416 KB46 MiB3.1 s2.0 s7.2 s

A store with no export took 0.02 seconds for the sample document and 0.17 seconds for the 521-page document.

  • Stores. Hocuspocus stores a room that people type in about every 10 seconds. For long documents, set exportIntervalMs, for example to 60,000. A store inside the interval is then cheap, but it writes a state that the server did not check.
  • Upgrades. One upgrade runs for each room, when its first participant opens it after a format change. To keep long upgrades off the server, lower maxUpgradeStateBytes and upgrade larger rooms in a migration job.
  • Processes. One Node.js process runs this work on one core. Put rooms with long documents on their own processes, and route each room to one process.
  • Memory. A load holds the room twice while it checks the stored state.
  • Storage. A room state holds each XML element and attribute as its own record, so it is about seven times the size of the uncompressed XML. It compresses well: gzip reduced the 4.2 MiB state to 0.46 MiB, and the 46 MiB state to 5 MiB. Compress the state in save, and decompress it in load.

Prepare the room document on a server

collaborationServerExtension does this step. If you write the hooks yourself and 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);
  },
});
  • documentName is untrusted client input. In production, check room access in onAuthenticate and 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. Without document.flush(), the first participant receives the loaded state twice.
  • A relay-only server with no Y.Doc needs no preparation.
  • Extension hooks run before the server's hooks. If an extension such as @hocuspocus/extension-database loads state, call prepareCollaborationServerDocument in your own extension's onLoadDocument with priority: 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, checkCollaborationRoomGeneration refuses old replicas with room-generation-changed.
  • With @hocuspocus/extension-database, seed in fetch with a create-only insert such as INSERT ... ON CONFLICT DO NOTHING, then read the row back. Hocuspocus does not call store for state that fetch returns.

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 maxBytes to 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 CollaborationSchemaError with baseline-too-large (before parsing), invalid-baseline, or invalid-document-id. A maxBytes that is not a whole number from 1 to 20 MiB throws TypeError.

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.

  • compactCollaborationState returns null when the stored state is less than twice a fresh build of the content.
  • It throws CollaborationSchemaError for 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 checkCollaborationRoomGeneration in beforeHandleMessage, 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;
  }
}
  1. Sync the provider before bootstrap: { kind: 'join' }, or the join fails with initialization-timeout after 30 seconds.
  2. Pass an Awareness from y-protocols/awareness for presence.
  3. Send connection events to session.setTransportStatus, or the status stays ready during an outage. The second argument is a CollaborationFailureCode; the third holds diagnostic text.
  4. Report rejected credentials as error with authentication-failed, because disconnected still 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 author on the runtime. TrackMineOnly persists across runs and does not change other participants' modes. Off makes permanent edits. TrackAll fails with NotSupported.
  • Tracked replacements stay within one paragraph. range.delete() and paragraph.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(), and canRedo() return false, and session.undoGroupOpen is true.
  • 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 returns true. The next undo() 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 refuses runtime.run({ historyGroup }) with NotSupported.

beginUndoGroup() throws CollaborationUndoGroupError:

CodeCauseAction
undo-group-already-openThe session has an open group.End it, or use another session.
editor-attachedAn editor is attached.Use editor.beginHistoryGroup(), or a separate agent session.
collaboration-session-destroyedThe 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 documentName in onAuthenticate.
  • 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 editsResult
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

LimitValueFailure codeRemedy
Seed document, compressed and uncompressed20 MiB, or a lower maxBytesbaseline-too-largeReduce the document.
Files in the seed document10,000invalid-baselineRemove parts.
One embedded file32 MiBblob-too-largeCompress the media.
All embedded files64 MiBblob-store-fullRemove media; create a new room.
Document nodes, deleted included200,000too-many-nodesExport; create a new room.
Nesting depth256 levelstree-too-deepFlatten nested tables or content controls.
Children of one node100,000too-many-childrenSplit the content.
Attributes of one element4,096too-many-attributesReduce the document.
Package parts512too-many-partsRemove parts; create a new room.
Relationships10,000too-many-relationshipsRemove links or media; create a new room.
Text in one paragraph1,048,576 characterstext-too-longSplit the paragraph.
One inserted text1,048,576 characterscollaboration-text-limitInsert smaller pieces. The session stays ready.
actorId, name, documentId, sessionId256 charactersinvalid-identity, invalid-document-id, invalid-session-idShorten the value.
Identity color64 charactersinvalid-identity-colorShorten the value.
Presence participants256NoneReads return the first 256.
Initial synchronization30 secondsinitialization-timeoutConnect 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. limit is nodes, parts, relationships, or blobBytes.
  • session.resourceUsage() returns each count beside its limit, such as nodes and maxNodes. On a server, readCollaborationResourceUsage(ydoc) reads a synced Y.Doc without joining or writing.
  • Both probes walk the node map. Read them on a schedule, not on every edit.
  • formattingMarkers counts the formatting markers in paragraph text. Deleting the formatted text does not remove them; compaction does.
  • When a limit ends the room, detail names it, such as nodes=200001.

Size a room server

These numbers come from the load benchmark in benchmarks/collaboration-server. Use them as a starting point, and run the benchmark on your hardware with your documents.

Each step ran one room for 60 seconds. Every participant typed at about 3.5 keystrokes per second. The server was one Node.js 24 process on an Apple M4 Pro laptop, and the participants ran on the same machine. The server stored the room and a DOCX export about every 10 seconds. The seed document was 75 KB, and the room state was about 4.3 MiB.

ParticipantsLatency p50 (ms)Latency p95 (ms)Join p95 (ms)Server CPU average (% of one core)Server memory peak (MB)Server egress (KB/s)
53.310.05766.845138
102.87.89197.3463149
153.412.61,4889.0458331
204.324.91,97110.7498584
255.443.72,51512.3554906

Latency is the time from a keystroke at one participant to that edit in another participant's document. It excludes the network round trip.

  • Memory: one room of this size held 450 to 550 MB. An idle server process used about 120 MB.
  • CPU: one more typing participant added about 0.3% of one core. One Node.js process runs JavaScript on one core.
  • Egress: it grows with the square of the participant count, because the server relays each edit and each caret to all others. Caret updates were about 70% of the bytes.
  • Exports block the server: each store exported the room, which took about 0.2 seconds. The server relays nothing during an export. See Plan for the cost of exports and upgrades.
  • Many rooms: multiply the cost of one room by the number of active rooms.
  • Shared machine: the participants shared the machine with the server. When other work ran on that machine, latency rose to seconds. For a strict measurement, run the participants on a second machine.

To run the benchmark, see the benchmark guide.

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).

CodeCauseRecoveryAction
collaboration-session-not-readyStatus is initializing, error, or disconnected with offlineEditing: false, or an update waits for a dependency.Refused editWait for ready.
collaboration-session-not-attachedNo editor attached its port.Refused editRemount with the room's modules.
collaboration-session-destroyedThe session was destroyed.Refused editMount a new session.
collaboration-text-limitOne insert exceeds the shared text limit.Refused editInsert smaller pieces.
experimental-collaboration-body-text-onlyA review write has no named intent.Refused editUse a named review command.
invalid-document-id, invalid-session-id, invalid-identity, invalid-identity-colorAn option is empty or too long. setIdentity also throws identity codes.ThrownFix the value.
already-initializedA create bootstrap found a seeded room.ThrownUse join or create-or-join.
document-id-mismatchThe room, or an attached editor, has another documentId.Thrown or terminalCheck both IDs.
initialization-timeoutNo synced room appeared in time.ThrownConnect the provider or raise the timeout.
initialization-abortedThe signal aborted, or the server refused the credential during the join.ThrownRefresh the credential and connect again.
not-initializedA server helper read an unseeded room.ThrownWait for sync. Create a room only if storage confirms none exists.
baseline-too-large, invalid-baseline, no-main-document-part, blob-read, missing-local-blobThe seed bytes cannot open as a document.ThrownFix or reduce the file.
collaboration-format-mismatch, protocol-version-mismatch, schema-version-mismatchClient and room formats differ.Thrown or terminalSave local work. Use a compatible deployment, or upgrade the saved room.
concurrent-seedTwo peers seeded the room at once.Thrown or terminalSave local work; create a new room from it.
blob-digest-mismatchAn embedded file does not match its digest.Thrown or terminalSave local work; create a new room from it.
port-already-attachedA second editor attached to one session.TerminalGive each editor its own session.
remote-apply-failed, materialize-dropped-content, missing-blob, missing-root, invalid-relationshipsA peer's update is incomplete, or a joined room forms no document.Heals; thrown during joinWait. If it persists, save and rejoin.
duplicate-paragraph-id, unknown-paragraph-idA custom integration sent a paragraph update the port cannot apply.Port resultUpdate 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-fullA document or edit crosses a numeric limit.Thrown, heals, or terminalA 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-nameShared state or an edit fails a trust-boundary check.Thrown, heals, or terminalTreat the room as untrusted. If it persists, use a new room.
transport-disconnectedThe connection dropped, or one WebRTC peer link cannot carry large updates.RecoversWait and show the status.
authentication-failedThe server rejected the credential after the join.TerminalRefresh the credential, then rejoin.
room-generation-changedThe server compacted or reseeded the room while this replica was away.TerminalSave unsent edits, then rejoin.
transportA hook could not connect, and the provider gave no recognized code.Hook errorFix the options and retry.
invalid-saved-room, saved-room-unavailableYour server refused to load a saved room.TerminalRepair 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.

See also