RebodocsDocs
Start3
What is Rebodocs
Getting started
Demos to run
Put it in your app8
React component
Headless: your own UI
A complete interface
Without a framework
Only to read: the viewer
Styling and Tailwind
Phones and touch
Accessibility
Documents8
Templates and variables
On a server: DOCX and PDF
Documents in an S3 bucket
Letterheads
Versions
Tracked changes
Fonts
Languages
Together2
Real-time collaboration
AI assistants (MCP)
Reference5
Packages
Components and hooks
Editor API
How it works
Status and roadmap
↑↓ to move↵ to openEsc to close26 pages

Together Real-time collaboration

Real-time collaboration

Several people on the same document at once, each seeing where the others are, with an undo of their own. The collaboration server only coordinates; your backend keeps the files and decides who may open them.

tip: hold the network below, and type in both

The people

Ana’s browser
Luis’s browser
Eva’s browser

Collaboration server

Rooms, in memory

One per document while someone is in it. Puts everybody’s changes in one order, and forgets the room when it empties.

Your backend

GET /docs/<id>

PUT /docs/<id>

POST /docs/<id>/access

Keeps the files and says who may come in: S3, R2, a disk, a database.

Live

Two people, one room

Ana and Luis in two real editors on this page. The changes travel in the format of @rebodocs/collab and are put in order by its own transform; only the network between them is this page’s, held in memory so you can stop it and choose who arrives first.

Opening the room…

Hold the network, type in both at the same place, then let one through first and the other after: the log shows the server moving the second change over the first, and the badge checks that all three documents are the same, with the digest the real server sends.

The rules

When two people change the same thing

What everybody ends with, whichever order the server takes the two changes in. The ones marked “Try it” are set up in the editors above.

What happens at onceWhat everybody ends with
Both type at the same place.Both texts, the one the server got first before the other.
One deletes a passage, the other types in the middle of it.The passage goes, and what was typed in it stays.
One splits a paragraph (Enter), the other types after that place.The text goes into the second half.
One joins two paragraphs, the other types in the second one.The text is in the joined paragraph, at the same place in it.
One formats a paragraph, the other splits it.Both halves have the formatting.
Both join the same two paragraphs.One join.
One deletes a paragraph, the other types in it.The paragraph’s text goes, and what was typed stays where it was, in a paragraph of its own with the same formatting. The one typing goes on typing there, without the caret jumping.
One deletes a paragraph, the other only formats its text or presses Enter in it.The paragraph is gone: nothing new was written in it.
One formats a passage (bold, a colour, a tracked deletion), the other types in it.What was typed stays where it was typed, without the formatting; the rest has it.
Both format the same passage.Each letter has the formatting of the one the server got last.
One formats a passage, the other deletes part of it.What was deleted is gone; the rest has the formatting.
Both put new paragraphs after the same one.Both, the ones the server got first before the others.
Both insert a table at the same place.Both tables, one after the other.
Both change the shape of the same table, the page setup, the styles or the same comment.The one the server got last. Cells left without a paragraph, or paragraphs in a cell that went, are mended the same way by everybody.
Both add a picture or a comment.Both: their names are made unique before they are sent.

These rules have unit tests for pairs of concurrent changes, and tests with two clients typing through a real server. test/convergence.test.ts makes two people edit at random — typing, deleting across paragraphs, Enter, bold, alignment — from 3,000 seeds, with one edit each and with up to three, and checks that both end with the same document whichever way round the server takes them. They all do. With more seeds and more edits a few still do not (6 in 20,000 with three edits each): both people cut, join and take out paragraphs around the same place at the same instant. Tables are not in the random edits, and concurrent changes to the structure of the same table are the weakest part.

Whatever the rules get wrong lasts seconds. A moment after the changes stop, the server tells the room a digest of its document. An editor whose document differs loads the room again, keeping what the person had typed and not sent; what they can undo starts over. See how it works inside.

Start here

A demo to run

apps/realtime is all of this page working: the collaboration server, a backend with the three routes and signed tickets, and the page. Nothing to set up.

git clone https://github.com/JFranciscoRobles/rebodocs && cd rebodocs && npm install
npm run realtime          # http://localhost:5177

Every document is a room. Open contract.docx, press Copy link and open the link in another window, or another browser; give each a name in You are. A room opens with the document the backend has, gives it back every 10 seconds while someone types, and once more a moment after the last one leaves. The demo starts the collaboration server in its own process, on port 7421, and reaches the backend as it would from anywhere: over HTTP, with the key. With the names of a bucket in apps/realtime/.env the documents go to S3 instead of a folder, with no other change. apps/assistant is the same demo with Claude in a chat beside the document.

server/collab.ts
The three routes, the log of each room as it comes, the tickets, the name of a room.
server/api.ts
What the page asks: the documents, a new one, a ticket.
server/store.ts
Where the documents are kept: a folder, or an S3 bucket.
server/versions.ts
A version for each session of work.
src/App.tsx
The page.
Your system

Set it up in three steps

The server, three routes in your backend, and a ticket for each person. No storage credentials reach the browser, and none reach the collaboration server.

1. Run the server

It is @rebodocs/collab on npm: plain Node with no dependencies. Put it behind HTTPS with your usual proxy; it uses server-sent events and POST, not WebSockets, so nothing special is needed.

REBODOCS_COLLAB_BACKEND_KEY=a-long-secret \
  npx @rebodocs/collab --host 0.0.0.0 --backend https://api.example.com/docs
--backend URL
Where documents are read from and saved to.REBODOCS_COLLAB_BACKEND
--backend-key KEY
Sent to your backend as Authorization: Bearer …, and what your backend shows to have someone’s access asked about at once. Put it in the environment, not on the command line.REBODOCS_COLLAB_BACKEND_KEY
--backend-log
Give your backend every change as it comes, on three more routes, so a server that stops all at once loses none.REBODOCS_COLLAB_BACKEND_LOG=1
--port N
7420 by default.REBODOCS_COLLAB_PORT
--host ADDR
The address to listen on: this machine alone when left out; 0.0.0.0 lets others in.
--save-after N
Seconds after the last change that the document is saved. 5 by default.
--save-every N
The most seconds a room with changes goes without being saved while people keep typing. 30 by default.
--recheck-every N
Seconds between asking /access again whether each person may still be in; whoever it turns away is sent out. Never by default: your backend can ask for it when it changes someone’s access.REBODOCS_COLLAB_RECHECK_EVERY
--instance NAME
What this process is called among several behind one address: said in X-Rebodocs-Instance on everything it answers, and by /collab/ping.REBODOCS_COLLAB_INSTANCE
--data DIR
Without a backend: the folder rooms are kept in, ./rooms when left out.
--memory
Without a backend: keep nothing, rooms last as long as the process.
--token WORD
Without a backend: the word a page must give to start a room.REBODOCS_COLLAB_TOKEN
--static DIR
Also serve a built editor from that folder: one address for the page and its rooms.

2. Three routes in your backend

Each request carries the key, so check it.

GET /docs/<id>
Someone opens a room nobody is in. Return the DOCX.
PUT /docs/<id>
--save-after seconds after the changes stop (at least every --save-every while they go on), when the last person leaves, on shutdown. Store the DOCX in the body. The one when the last person leaves ends a session of work, and says so.
POST /docs/<id>/access
Someone joins, with { "ticket": "…" }; and every --recheck-every seconds while they stay. Answer { "name": "Ana" } to let them in under that name, with "readOnly": true to let them only watch, or 403.

A sketch, with Next.js route handlers:

// app/api/docs/[id]/route.ts
const allowed = (request: Request) => request.headers.get('authorization') === `Bearer ${process.env.REBODOCS_COLLAB_BACKEND_KEY}`;

export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
  if (!allowed(request)) return new Response(null, { status: 401 });
  const file = await storage.get(`docs/${(await params).id}.docx`);
  return file ? new Response(file) : new Response(null, { status: 404 });
}

export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
  if (!allowed(request)) return new Response(null, { status: 401 });
  await storage.put(`docs/${(await params).id}.docx`, await request.arrayBuffer());
  return new Response(null, { status: 204 });
}
// app/api/docs/[id]/access/route.ts
export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
  if (!allowed(request)) return new Response(null, { status: 401 });
  const { ticket } = await request.json();
  const user = await verifyTicket(ticket, (await params).id);    // your own signed, short-lived token
  return user ? Response.json({ name: user.name }) : new Response(null, { status: 403 });
}

3. Give each person a ticket

A ticket is whatever your backend can verify: a signed, short-lived token saying who the person is and which document they may open. Make it when you render the page, and pass it on. The demo signs the room, the name and when it expires with a secret only the backend has, so it keeps nothing to check one.

<DocsEditor collab={{ url: 'https://collab.example.com', room: documentId, ticket }} />

The document comes from the room, so docx is not used; it saves itself through your backend, so onSave is not needed either.

Versions

A version for each session

The PUT made when the last person leaves, if anybody changed anything, says so: the moment to keep a version, signed by who worked on it, and not one every 30 seconds.

X-Rebodocs-Session-End: 1
This is the document as the session of work leaves it: everybody has gone.
X-Rebodocs-Authors
Who changed it in the session, as /access named them, each URL-encoded, separated by commas, in the order they first changed it. Someone who only looked is not there.
export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
  if (!allowed(request)) return new Response(null, { status: 401 });
  const id = (await params).id;
  const docx = new Uint8Array(await request.arrayBuffer());
  await storage.put(`docs/${id}.docx`, docx);
  if (request.headers.get('x-rebodocs-session-end') === '1') {
    const authors = (request.headers.get('x-rebodocs-authors') ?? '').split(',').filter(Boolean).map(decodeURIComponent);
    await storage.put(`versions/${id}/${Date.now()}.docx`, docx, { authors });
  }
  return new Response(null, { status: 204 });
}

Give the editor those versions (versions of DocsEditor) and everybody in the room can see them, compare the document with one, and go back to one: going back is one more change, sent to the others. A session ends when the room is let go of, idle after the last person left (30 s by default); someone who comes back before that is in the same session. A server that stops while people are in it gives the document back without the headers. See versions.

No lost work

When the server stops all at once

By itself the server gives your backend the document a few seconds after the changes stop: if it is killed before, those seconds of work are gone. With --backend-log it gives your backend every change as it comes, and none is lost.

The log is lines of text, one per change, after one with the file they are made to. Keep them as they come and give them back as they were: a file, a row, an object in a bucket. A room that opens with a log starts again from where it was, with the same epoch, so the editors that were in it come back as from a dropped connection, with what they had not sent. Each change goes as soon as it comes, one request at a time: what can still be lost is what was on its way.

PUT /docs/<id>/changes
A room has its first change, or its changes were folded into a new file while people stay. Store the body in place of any log there was: its first line, the file the changes are made to.
POST /docs/<id>/changes
Each change, as it comes; what comes while one is on its way goes with the next. Add the lines of the body after those there are. X-Rebodocs-From says how many came before them: answer 409 when that is not how many you have.
GET /docs/<id>/changes
Someone opens a room nobody is in, before GET /docs/<id>. Return every line as it came, or 404 when there is no log.
// app/api/docs/[id]/changes/route.ts — with --backend-log: lines of text, kept as they come
const logOf = async (params: Promise<{ id: string }>) => `logs/${(await params).id}.jsonl`;

export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
  if (!allowed(request)) return new Response(null, { status: 401 });
  await storage.put(await logOf(params), await request.text());          // a log starts
  return new Response(null, { status: 204 });
}

export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
  if (!allowed(request)) return new Response(null, { status: 401 });
  const key = await logOf(params);
  const log = (await storage.getText(key)) ?? '';
  // Optional: none went missing in between.
  if (Number(request.headers.get('x-rebodocs-from')) !== log.split('\n').filter(Boolean).length - 1) return new Response(null, { status: 409 });
  await storage.put(key, log + (await request.text()));                 // more lines, after those
  return new Response(null, { status: 204 });
}

export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
  if (!allowed(request)) return new Response(null, { status: 401 });
  const log = await storage.getText(await logOf(params));
  return log ? new Response(log) : new Response(null, { status: 404 });
}

// And in PUT /docs/<id>: the session ended, so the document is the whole of it.
if (request.headers.get('x-rebodocs-session-end') === '1') await storage.delete(`logs/${id}.jsonl`);

The PUT of the document that ends a session ends the log too: let it go then, in the same request. A log left behind, by a server that stopped, is how the room picks up again; it is not a history. In code it is backendStorage({ url, key, log: true }).

Access

Taking access away

The ticket is checked when someone comes in. When your system takes their access away, or lets them only watch, have the server ask again at once.

// Your backend, when it takes someone's access away or changes it
await fetch(`https://collab.example.com/collab/rooms/${documentId}/recheck`, {
  method: 'POST',
  headers: { Authorization: `Bearer ${process.env.REBODOCS_COLLAB_BACKEND_KEY}` },
});

With --backend-key, POST /collab/rooms/<id>/recheck asks /access again for everybody in that room, and POST /collab/recheck for every room of the process. Whoever it no longer lets in is sent away, and their editor says they no longer have access; whoever it now lets only watch, or edit, comes back as that. Without a key there is no such route; --recheck-every asks every so many seconds instead, and server.recheck(id) does it from code.

Scale

Several processes

A room is held by one process, in its memory. To run several, send every request of a room to the same one: the id of the room is in the address.

# nginx: each room to one process, by the id in its address
map $uri $room { ~^/collab/rooms/([^/]+) $1; default $uri; }

upstream collab {
  hash $room consistent;
  server 10.0.0.11:7420;
  server 10.0.0.12:7420;
}

server {
  location /collab/ {
    proxy_pass http://collab;
    proxy_http_version 1.1;
    proxy_buffering off;        # the stream of events
    proxy_read_timeout 1h;
  }
}

It takes --backend, so that any process can open any document, and --backend-log, so that a room whose process stops opens in another where it was: its editors come back to the address they had, and the balancer sends them to the one that has it now. --instance names each process, in X-Rebodocs-Instance, to see where a room is. Should a room open in two processes at once, while the balancer changes, your backend’s 409 to the log says so. A recheck for every room reaches only the process the request goes to: ask room by room.

In the editor

What people see

Each other

The others’ carets and selections, each in a colour with their name, and who is on the document in the status bar.

Their own undo

Undo takes back your own steps and leaves the others’ in place.

No lost work

If the connection drops, the editor says so, keeps working, and sends what was typed when it comes back.

From outside

onCollab={(state, peers) => …} tells your application the same: state is 'connecting', 'on' or 'offline'.

Inside

How it works inside

What travels, in what order, and what the editor does with it. None of it is needed to use the component.

Paragraphs by id, not by place

Everybody in a room starts from the same file, and stampIds gives each paragraph an id from where it is in that file: whoever reads the same file gets the same ids, without saying anything to anybody. A paragraph made later gets an id minted by the editor that made it (<client>.<n>), so two people can never make the same one.

A change names the paragraph it is about by that id. "In k3, at offset 12, insert x" still means the same after someone added ten paragraphs above k3, which "in paragraph 4" would not.

Headers, footers, footnotes and text boxes are stories, with paragraphs and ids of their own. A change to one carries its part (header, firstFooter, the header of a section, footnote:<id>, textbox:<id>…), so a caret in a footer, or text typed in a text box, goes to everybody like text in the body.

What a change is

An editor does not send keys or documents. Every time the document changes, it compares it with the last one it sent (diff) and sends what is different, as a list of operations:

Operation What it says
splice In paragraph id, at at, take out remove characters and put in these runs, with their formatting. Typing, deleting, pasting and formatting part of a paragraph are all one.
split, join A paragraph cut in two at a place, with an id for the second half; two paragraphs made one.
insert, delete Whole paragraphs put in after another (or at the start), or taken out.
para The formatting of a paragraph: only what changed of it, null for what was taken away. Also the cell it is in and the section it ends.
table The shape of a table as a whole: rows, columns, widths, merged cells.
story A header, footer, footnote or text box made, or taken away.
set Something of the document as a whole: page setup, columns, styles, the first page of its own, whether changes are tracked.
note, media, num A comment, a picture's bytes, a list definition.

Formatting is part of the runs, and so are tracked changes: a deletion someone makes with tracking on travels as a splice that marks the text deleted, and everybody sees it struck through, signed with that person's name.

The format is in @rebodocs/collab, and none of it needs a browser:

import { stampIds, ensureIds, diff, apply, transform } from '@rebodocs/collab';
import { importDocx } from '@rebodocs/core';

const before = stampIds(importDocx(file));
const after = ensureIds(before, editSomehow(before), mint);
const ops = diff(before, after);       // what turns one into the other
apply(before, ops);                     // the same document as `after`

One order for everybody

The server keeps, for each room, the file it started from and a log of every change since, numbered. That log is the one order everybody follows.

An editor sends its changes with the number of the last one it had seen (rev). If others got there in between, the server does not refuse it: it transforms it against those, so that it means what its author meant on the document as it now is, adds it to the log and tells everybody. Each editor makes the changes of the log in order, and so they all end with the same document.

An editor sends one batch at a time and waits for it to take its place; what is typed meanwhile is gathered for the next. Each batch has a sequence number, so one sent again because its answer was lost is taken once.

The check against the room

The rules are not all there is. The server checks that everybody has its document: a moment after the changes stop (1.5 s, or every 6 s while they go on), it tells the room, in sixteen letters, what its document is like: a digest of the text, paragraph by paragraph, with its formatting and the shape of its tables. Each editor makes the same digest of the document it has from the room, and if it is not the same, it loads the room again: its file and every change made to it. What the person had typed and the room did not have yet is made again on it and sent, so nothing they wrote is lost; what they can undo starts over. So whatever the rules get wrong, it lasts a couple of seconds, not until someone opens the document again. session.resyncs says how many times it happened, and the console says it each time.

A deletion carries the paragraph it takes out, Enter the formatting of the new paragraph, and formatting says that it is formatting: older editors send changes without them, and their changes are taken the way they were before. Clients of different versions in the same room can end with different formatting, and an editor of before does not check its document against the server's, so update the editors and the server together.

What the editor does with it

  • What the person does is shown at once. The editor does not wait for the server. When someone else's change arrives first, it is made on the document the server confirmed, and what this person has not had confirmed yet is transformed against it and made again on top.
  • Undo is per person. Each step is kept as the changes that undo it, not as the document as it was. When others' changes arrive, the steps kept are transformed against them too, so undoing takes back what you did and leaves what they did after.
  • Carets are places by id. Where each person is goes as a paragraph id and an offset, with the part and the page, about 40 ms after it moves. As changes arrive, the carets of the others are carried through them.
  • Checked against the room. The editor compares its document with the digest the server sends now and then, and loads the room again when they differ (see above).
  • Reconnection. If the stream drops, the editor goes on working (state is 'offline') and tries again after 0.5 s, then 1, 2, 4, up to 8 s. Coming back, it says how far it had got; the server sends only what it missed, and what it had sent without an answer is sent again. If the room was folded into its file meanwhile (see below), or let go of and read again from your backend, it loads the room again from the start, and what was typed while away is not lost: it tells which paragraphs of the file are those it had by what they read, takes what the others did meanwhile as the change from the one to the other, and makes what was typed after it, as if both had typed at once. What the server had said it took is in the file already, and is not made twice; what can be undone starts over. A room that is not there (404), a person no longer let in (403), or one the server sent away (removed) ends the session.
  • Its own key. Coming in, the editor is given a key only it knows, and everything it sends carries it. The others know its id, to draw its caret, but cannot send as it: someone let in only to watch cannot pass their changes off as an editor's.

The life of a room

  1. It opens when someone comes in and nobody is in it: the server asks the storage for the file (with a backend, GET /docs/<id>).
  2. While people are in it, every change goes into its log in memory, and the server gives the backend the document as it is (PUT) saveAfter after the changes stop (5 s by default), and at least every saveEvery (30 s) while they go on. Once the log has foldAfter changes (1000), the server folds them into the file at the next pause, with everybody still in: whoever comes in then has the file and few changes to make, not the whole day's.
  3. When the last one leaves, the server waits idle (30 s by default), makes the changes into one file, saves it, and lets the room go. That PUT says the session ended, and who changed the document in it: a version for each session. Someone who comes back meanwhile finds it as it was.
  4. On shutdown (SIGINT, SIGTERM) the command gives the backend what it does not have yet before leaving. In a program of your own, call server.flush().

Each time the changes are folded into the file, the room's epoch goes up: a client that had the room before it was folded knows its numbers no longer apply, and loads it again. Folded while people are in it, the file read again gives some paragraphs other ids than they had; the server tells the editors which (fold), and each loads the new file and makes on it what it had not sent, with what it can undo, under the new ids. The server folds only when the file reads back as the document it was written from; otherwise the changes wait for the room to empty, as before.

Reference

The server in your own program

Its options and storage, mounted inside the API you already have, what goes over the wire, and the editor without React.

The server in a program of your own

import { createCollabServer } from '@rebodocs/collab/server';
import { backendStorage } from '@rebodocs/collab/storage';

const server = createCollabServer({
  port: 7420,
  host: '0.0.0.0',
  storage: backendStorage({ url: 'https://api.example.com/docs', key: process.env.KEY, log: true }), // log: every change as it comes
  saveAfter: 5_000,    // ms after the last change the document is given to the backend
  saveEvery: 30_000,   // and at least this often while people type
  idle: 5_000,         // ms a room nobody is in waits before it is saved and let go of
  checkAfter: 1_500,   // ms after the last change the room is told what its document is like
  foldAfter: 1_000,    // changes a room gathers before they are folded into its file, with people in it
  recheckEvery: 300_000, // ms between asking the backend again who may be in; never when left out
  recheckKey: process.env.KEY, // what the backend shows to POST /collab/rooms/<id>/recheck
  instance: 'collab-1', // this process, among several: in X-Rebodocs-Instance
  onEvent: (event) => log(event), // join, leave, fold, save, removed, error
});
await server.ready;

server.rooms();        // [{ id, people: ['Ana', 'Luis'] }]: who is where, for a list of open documents
await server.recheck(documentId);   // someone's access changed: ask now, not at the next recheckEvery
process.on('SIGTERM', () => void server.flush().finally(() => server.close()));

The storage is an interface, so the backend over HTTP is one of three that come with it, and you can write your own (straight to a database, say):

Storage What it keeps
backendStorage({ url, key }) Nothing: the documents are your backend's, and it says who comes in.
folderStorage(dir) Each room in a folder: base.docx, log.jsonl with every change, meta.json. The file and log before the last fold stay beside them, as *.before.*.
memoryStorage() Nothing at all: rooms last as long as the process.

recheck asks /access again with the ticket each person came in with: whoever it no longer lets in is sent away, and whoever it now lets only watch, or edit, comes back as that. Tickets that expire are asked about as they are, so make them last as long as a session may, or leave recheckEvery out and call recheck when your system takes someone's access away. Given onEvent, what goes wrong goes to it rather than to the console.

A RoomStorage has load(id) and keep(id, room, folded) for the file, add(id, entry) for each change, and optionally save(id, docx) for the document while people work, and admit(id, ticket) to say who may come in, under what name, and whether only to watch ({ name, readOnly: true }). Someone let in to watch sees the others type and cannot change anything: the editor goes read-only, and the server refuses their changes. /access says it the same way, with "readOnly": true.

Inside your API, on its port

Left without port, the server listens on none: mount its handle in the server your API already has, and the room storage can call your services straight, without the three routes:

const collab = createCollabServer({
  storage: {
    open: false,
    forgets: true,
    // A new epoch each time: an editor that had the room before it was let go of knows the file may have changed.
    load: async (id) => ({ name: await documents.name(id), epoch: Date.now(), base: await documents.read(id), log: [] }),
    keep: async (id, room, folded, ended) => { if (folded) await documents.write(id, room.base, ended?.authors); },
    add: () => {},
    save: (id, docx) => documents.write(id, docx),
    admit: (id, ticket) => tickets.check(id, ticket),   // { name, readOnly? } or undefined
  },
  saveEvery: 10_000,
});

app.use('/collab', collab.handle);   // Express; in Nest, app.use in main.ts

It reads the address from originalUrl, so the prefix Express takes off does not matter, and takes a body your body parser already read. Its routes answer with Access-Control-Allow-Origin: * and need no cookies: the ticket is what lets someone in. One process still holds each room, so run one instance of the API, or route each room to one.

On the wire

Everything is under /collab, as plain HTTP: one stream of server-sent events per person, and POSTs to send. Any proxy that passes HTTP passes it; turn response buffering off for the events route (the server already sends X-Accel-Buffering: no for nginx).

Route What it is
GET /collab/ping Whether a collaboration server answers, the version of the protocol it speaks (collab), whether starting a room needs a token, and its instance when it has one.
POST /collab/rooms Starts a room with a document (without a backend only).
POST /collab/rooms/<id>/recheck, /collab/recheck Ask the backend again who may be in that room, or in every room; with recheckKey, as Authorization: Bearer ….
GET /collab/rooms/<id>/events With v, the version of the protocol the editor speaks: one this server does not is answered 426, with the one it does. The stream: hello (the room, the changes the client lacks, who is in, and the client's key), then op, presence, leave, check (the digest of the document at a revision), fold (the changes folded into the file, and the paragraphs' new ids) and removed. A comment every 20 s keeps it open.
POST /collab/rooms/<id>/ops A batch of changes, with client, key, rev, epoch and seq.
POST /collab/rooms/<id>/presence Where this person's caret is, with client and key; 64 KB at most.
GET /collab/rooms/<id>/base, /docx The file the room started from; the document as it is now. Only for someone in the room (client and key), when there is a backend.

Each person may send 200 at once and 50 more a second, far more than an editor does; past that the server answers 429 and the editor tries again.

Without React

DocsEditor with collab does all of this. With the editor alone, joinRoom takes any Editor; once its state is 'closed', its reason says why: 'left', 'not-found', 'denied', 'removed' (sent away) or 'outdated' (the editor and the server speak different versions, PROTOCOL):

import { Editor } from '@rebodocs/editor';
import { joinRoom } from '@rebodocs/collab/browser';

const editor = new Editor(element);
const session = joinRoom(editor, documentId, {
  url: 'https://collab.example.com',
  ticket,
  onChange: () => render(session.state, session.peers),
});

session.pending;     // changes made here the server has not taken yet: worth checking before closing the page
session.resyncs;     // times the document here was found not to be the room's, and loaded again
session.leave();     // stops sharing; the document stays as it is

createRoom(url, docx, name, token?) starts a room with a document of the person's own (without a backend), and pingServer(url) says whether a server is there.

Trying it without a backend

npx @rebodocs/collab                 # keeps rooms in ./rooms
npx @rebodocs/collab --memory        # keeps nothing

In the playground, the "Share" button of the status bar starts a room and gives a link to pass on.

Limits

What to know

Collaboration has run with two tabs, two browsers on a local network and between different networks behind an HTTPS proxy, over a real bucket; the demo’s backend has automated tests with two people typing through it, over a folder.

  • A room is named with letters, digits, - and _, from 8 to 64 of them. The id of a document in your system will do; the demo, which has file names, uses a digest of the name.
  • One process holds a room: with several, route each room to one of them (see Several processes).
  • The ticket is checked on joining, and again when your backend asks for it, with --recheck-every or server.recheck(): otherwise someone whose access you revoke stays until they disconnect.
  • Without --backend-log, a hard crash loses the changes since the last save: up to --save-after seconds (5) after people stop typing, up to --save-every (30) while they go on.
  • The server keeps no versions: your application does, and the editor compares and restores them. Who changed what travels with tracked changes.
  • An editor and a server that speak different versions of the protocol do not meet: the editor is turned away and says one of them needs updating (session.reason is outdated).