# Real-time collaboration

> Several people edit one document at once, see each other's cursors and share comments and suggestions through a collaboration server you host.

URL: https://editor.vivepdf.com/en/docs/collaboration/
Last updated: 2026-11-29

Several people edit the same document at the same time. Everyone sees the others' cursors and names, a button in the toolbar shows who is in the document, and comments and suggestions are shared as they are written. Undo and redo only touch your own changes.

Collaboration needs three parts:

- **The editor** in the browser, with `@viveeditor/collab`. It is in the one-script build as an add-on.
- **The collaboration server** `@viveeditor/collab-server`, a WebSocket server on Node 22.12 or newer that you run yourself, behind TLS.
- **Your application**, which signs a short-lived token for each person and document and stores the documents through two hooks.

## One-script build

Point the textarea at the document and at a token address on your own site:

```html
<textarea name="body" data-editor
  data-collab-document="report-2026"
  data-collab-token-url="/collab-token"
  data-threads="body-threads">…</textarea>
<input type="hidden" id="body-threads" value="[]">
```

- `data-collab-document` names the shared document. `data-collab-token-url` must be on the same origin as the page.
- The editor asks the token address with `POST` and the JSON body `{ "document": "report-2026" }`, sending the page's cookies. Answer with `Content-Type: application/json` and `{ "url": "wss://collab.example.com/collab", "token": "…" }`. The editor connects only to the `url` your answer names, never to an address taken from the page, and a renewal that names another server is refused.
- Answer `401` or `403` when the person may not open the document; the editor then stops asking.
- The add-on `viveeditor.collab.iife.js` loads only on pages with these attributes and is checked against a `sha384` fingerprint, like the other add-ons.
- With `data-threads` the comments panel is shared through the server. The hidden field is not written, so a form post cannot change comments past the server's checks.
- Suggestions are written under the signed-in person, autosave and local drafts are off, and resetting the form does not replace the shared text.
- The textarea's text fills a document only when the server has never stored it; after that the server's copy wins.
- If an attribute is missing, the token address is on another origin, the answer is invalid or the add-on cannot load, the editor stays read-only and writes the reason to the console.

The server must build the same schema as the one-script editor: pass `classicExtensions` from `viveeditor` as its `extensions`.

## With npm

1. Install the packages: `npm install @viveeditor/collab @viveeditor/core @viveeditor/ui`.
2. Create the provider and, for shared comments, the thread store, before the editor.
3. Add `Collaboration` to the extensions and the people button and comments panel to the plugins.

```ts
import { Collaboration, createCollabProvider, followCollabUser } from '@viveeditor/collab'
import { createSharedThreads } from '@viveeditor/collab/threads'
import { createUI } from '@viveeditor/ui'
import { collabPresence } from '@viveeditor/ui/collab'
import { commentsPanel } from '@viveeditor/ui/review'
import { classicPreset, Editor } from 'viveeditor'
import 'viveeditor/style.css'

const provider = createCollabProvider({
  url: 'wss://collab.example.com/collab',
  document: 'report-2026',
  getToken: () => askToken('report-2026'),
})
const threads = createSharedThreads(provider)

const editor = await Editor.create(document.querySelector('#editor'), {
  extensions: [...classicPreset('en'), Collaboration.configure({ provider })],
})
const stopFollowing = followCollabUser(editor, provider)

const ui = createUI(editor, {
  plugins: [
    collabPresence({ provider }),
    commentsPanel({ threads, user: () => threads.author }),
  ],
})
```

- `getToken` returns a fresh token string from your token endpoint (`askToken` above is your own function). The provider calls it before every sign-in and before the old token runs out. Throw an error with `denied: true` (for example after a `401` or `403`) to stop at once; after five failed calls in a row the provider stops as well.
- Addresses must use `wss://`; `ws://` is accepted for `localhost` only.
- `followCollabUser` writes suggestions under the signed-in person. Call the function it returns, then `ui.destroy()`, `editor.destroy()`, `threads.destroy()` and `provider.destroy()` when the page leaves the document.
- Without the full `viveeditor` package, import `@viveeditor/collab/style.css` for the cursors.
- `Collaboration.configure({ provider, cursors: false })` hides other people's cursors.
- `provider.on('status', ({ status }) => …)` reports `connecting`, `connected`, `offline`, `too-large`, `refused` (the server did not accept a change and closed the connection; reload to continue), `diverged`, `denied` and `reset`, and `provider.on('access', ({ access, moderator }) => …)` reports access changes. The people button already shows both.
- `too-large` means the last change is larger than the server takes, or the document is full. The change stays only on this device while the connection stays open and others' changes keep arriving. It is sent once it fits again, for example after undoing it; the people button offers **Try again** and the page asks before closing. It is lost if the tab closes anyway, unless the offline copy is on.
- `diverged` means the server refused this browser's own copy right after connecting, usually because the server lost changes the copy is built on (for example after a backup was restored with the old epoch). The browser stops reconnecting and the people button tells the writer to copy their text. `provider.localDocument` then holds that copy as ProseMirror JSON (`null` in every other state), so the app can offer it, for example with `editor.setContent(provider.localDocument)` in a separate, unshared editor or as a download, before the page is reloaded.

### Offline copy

`offline: { userId }` keeps a copy of the document in the browser's IndexedDB, so it opens without a network and changes made offline are sent later:

```ts
createCollabProvider({ url, document, getToken, offline: { userId: session.userId } })
```

The copy is kept per person and document and is wiped when another person signs in, when the server replaces the document or when the token address refuses access. Copies of other documents stay in the browser until that person opens them again or you call `clearAllOfflineData()`, so call it when someone signs out on a shared computer.

## React, Vue, Svelte and Angular

The framework components take the same extensions and plugins. They read `extensions` and `ui` once, when the editor starts, so create the provider first and start a new component when the document changes (for example with `key={documentId}` in React). `value`, `v-model`, `bind:value` and form values never replace the shared text; only the starting value of a new document is used. See [Frameworks](https://editor.vivepdf.com/en/docs/frameworks/#collaboration).

## The server

```sh
npm install @viveeditor/collab-server viveeditor
```

```js
import { createServer } from 'node:http'
import { createCollabServer } from '@viveeditor/collab-server'
import { classicExtensions } from 'viveeditor'

const collab = createCollabServer({
  origins: ['https://app.example.com'],
  extensions: classicExtensions,
  async authenticate({ token, document }) {
    const session = await verifyToken(token, document)
    if (!session) return null
    return {
      access: session.canWrite ? 'write' : 'read',
      user: { id: session.userId, name: session.name, color: '#1d4ed8' },
      expiresAt: session.expiresAt,
      moderator: session.isModerator,
    }
  },
  load: (document) => database.loadDocument(document),
  store: (document, stored) => database.saveDocument(document, stored),
  loadThreads: (document) => database.loadThreads(document),
  storeThreads: (document, threads) => database.saveThreads(document, threads),
})

const server = createServer()
server.on('upgrade', (request, socket, head) => collab.handleUpgrade(request, socket, head))
server.listen(1234, '127.0.0.1')
```

- `extensions` must be the list the editor uses. A browser with a different schema is refused.
- `origins` lists the page origins that may connect, matched exactly.
- `authenticate` checks the token and returns a grant, or `null` to refuse. The grant runs out at `expiresAt`, at most one hour ahead, and the browser renews it with a new token. A renewed token never raises access or gives moderator rights.
- `load` returns `{ state, epoch, owners }` or `null` for a new document, and `store` receives the same shape; store it as you got it. Changes are stored two seconds after the last edit, at most every 30 seconds while people keep typing, when the last person leaves and on `close()`.
- After restoring a backup, return a new `epoch` with it. Browsers that had the document open drop their local copy and load the restored one cleanly; with the old epoch, a browser holding changes the backup does not have ends in `diverged`.
- `loadThreads` and `storeThreads` share comments. Without them, the comments panel cannot save in a shared document.
- Run one process per document. Two processes serving the same document would each keep their own copy.
- Put the server behind a TLS proxy so browsers connect with `wss://`. Behind a proxy, pass `address` so the per-address limits see the real client.
- Pass `workers: { module: new URL('./schema.js', import.meta.url) }` to check changes in worker threads, so one large change does not hold up other documents. The module exports the same list as `extensions` (`export const extensions = [...]`). If a worker stops, its documents reconnect and load again from storage. Each worker may use at most `memory` megabytes of heap (default 4096), so a worker that runs out stops alone instead of the whole process.

The repository has a runnable example server in [`packages/collab-server/example`](https://github.com/mtvrkan/viveeditor/tree/main/packages/collab-server/example) with signed tokens, revocation and in-memory storage. Its README lists every setting.

## Tokens

Your application serves tokens from an endpoint of its own:

- Sign a token per person and document that lives five minutes at most, names the document, the person and the collaboration server (the audience), and is compared in constant time.
- Decide the document, the access and moderator rights on the server, from your own permission records for the signed-in person. Never take them from the request.
- Accept only `POST` from your own pages: check `Origin` or `Sec-Fetch-Site: same-origin`, or require a CSRF token, and use `SameSite=Lax` or `Strict` session cookies. Send no CORS headers, and refuse a request whose `Content-Type` is not `application/json`.
- Answer with `Cache-Control: private, no-store` and `X-Content-Type-Options: nosniff`, and never redirect.

## Who may do what

- **Writers** edit the text, add suggestions and comment.
- **Readers** see the text, the cursors and the comments, but cannot change anything. The server refuses their changes, and the editor stays read-only for them. Their toolbar keeps only the people button, the comments tool and the word count.
- **Moderators** (`moderator: true` in the grant) may also change and delete other people's comments. Everyone else changes only their own.
- `collab.setAccess({ document, userId }, 'read' | 'write', { moderator })` changes access at once; leave out `document` for every document of that person, or `userId` for everyone in a document. `collab.revoke({ document, userId })` closes the matching connections. Also stop accepting their tokens in your own system, or they can sign in again.
- `canResolve` decides who may resolve or reopen a comment thread. By default every writer may.

The server writes every comment under the signed-in person and its own time, whatever the browser sends. A suggestion must carry the signed-in person; its time comes from the writer's device and may be at most ten minutes ahead of the server clock (`clockSkew`), while earlier times are kept because changes made offline arrive later. Use ids that mean nothing outside your app for `user.id`, never e-mail addresses: everyone in the document receives them with comments and suggestions.

## What the server checks

- Every change a writer sends is checked against the editor schema before it is applied: only elements, attributes and marks the schema knows, values that pass its validators, content where the schema allows it, children of new elements in the order the schema asks for, attributes without a default that stay on their element, limited depth and size. The depth limit is 32 levels by default, the same limit the editor keeps while you write (15 list levels at the top of the document), so a writer is never disconnected for indenting; if you lower `limits.depth`, writers can reach it. A change that fails is not applied and the writer is disconnected. A whole document's content rules are checked before each store; a document that breaks them is still stored and reported through `onEvent`.
- A suggestion must carry the writer's own name. Someone else's suggestion can only be moved, never rewritten or turned into another kind of suggestion, and text typed inside it is written as the typist's own. The order of moved text is checked within each paragraph: text moved out of someone else's suggestion may come back spread over several paragraphs in another order between them, and one of their changed paragraphs may come back split into several paragraphs that each carry their change. Undoing the deletion of someone else's suggestion brings their text back as new text under their name, so the server refuses that change like any other forged suggestion; ask the author to restore it, or reject the deletion instead.
- A cursor id belongs to the first person who writes with it; nobody else can write or show a cursor under it. The record is stored with the document, so it holds after a reload.
- Connections, messages, cursor updates, comments, documents open per person (5), document size and the number of items in a document have limits. Each one has a default in `DEFAULT_LIMITS` and can be changed through `limits`.
- One change may be as large as a whole document (10 MB by default), so a large Word file can be opened or pasted at once. Your proxy must let WebSocket messages of that size through.
- An open document takes six to nine times its stored size in server memory. Lower `rooms` and `documentSize` to fit your machine; the README of the server package has the figures.
- Each person may ask for at most 40 MB of document state a minute (`outgoingBytes`).
- The schema check compares element, mark and attribute names and the `configure()` options that change what a document may hold, and each attribute's validator name, but not the validator functions themselves. A custom extension whose validator depends on its options should return those options from `schemaOptions`. Give the server exactly the same extensions and options as the editor.
- `onEvent` receives sign-ins, refusals, closes and failures for your logs, without tokens or document content.

## Saving and publishing

The collaboration server keeps the shared copy through `store`; it is the copy the editor opens next time. For your own pages, save HTML as you do without collaboration: the one-script form still posts the current HTML under the textarea's name, and with npm you send `editor.getHTML()`. Check on your server that the person may save the document, and clean the HTML with [the server sanitizer](https://editor.vivepdf.com/en/docs/server-sanitizing/) before you publish it. Its defaults remove comment anchors and pending suggestions.

The File menu still saves and opens Word and Markdown files. In a shared document, opening a file asks first, because its content is inserted at the cursor for everyone.

## Related pages

- [Comments](https://editor.vivepdf.com/en/docs/comments/)
- [Track changes](https://editor.vivepdf.com/en/docs/track-changes/)
- [Frameworks](https://editor.vivepdf.com/en/docs/frameworks/)
- [Security and CSP](https://editor.vivepdf.com/en/docs/security-and-csp/)

## Do I need a paid service or a third-party server?

No. `@viveeditor/collab-server` is a Node package you run on your own server. The documents, comments and names stay on it and in your database.

## Does the editor still work without the collaboration server?

Yes. Collaboration is optional. Without it the editor works as a normal form field. If a shared editor cannot reach the server, it waits read-only and connects again on its own.

## Who decides who may write?

Your application. It signs a short-lived token for each person and document, and the server gives read or write access from it. Readers get an editor they cannot change, even through commands.

## Can people keep typing when the connection drops?

Writers keep editing while offline, and their changes are sent when the connection comes back. They are lost if the tab closes first, unless you turn on the offline copy.
