Real-time collaboration
Keep several copies of a PDF in step with NexPDF Sync and the NexPdfSync client over WebSocket or Server-Sent Events, push and receive changes to pages, annotations, comments, form values and bookmarks, show who else is in the document, with NexPDF for Node.js.
License module
Sync needs the annotations module (Indie tier and above).
NexPDF Sync lets several copies of one PDF (the browser viewer, apps, a server) edit the same document at the same time and converge. Copies exchange records with stable ids, not whole files:
Record type | What | id |
|---|---|---|
page | One page: its dictionary and its place in the document | Stored on the page |
annotation | An annotation that is not a reply | Its /NM |
comment | A reply in a comment thread | Its /NM |
field | The value of a form field | field:<full name> |
bookmark | One outline item | Its /NM |
object | A shared object: an appearance stream, font, image or content stream | obj:<hash> of its content |
Page operations sync: inserting, deleting, moving, rotating and cropping pages and editing their
content merge into one page order on every copy, and /Dest destinations follow their page. An
object record is sent once, however many records use it, and a copy that already holds the same
object uses its own: shared, not copied. Change sets have the format nexpdf-sync/2; format 1 is
still read.
Edits made with any other call are picked up automatically: every export and apply first finds the records that were added, changed or removed since the last sync. The sync state is saved in the PDF, so a reopened file continues where it left off.
The sync client
NexPdfSync from @nexdevit/nexpdf-node/sync connects a document to a NexPDF WebViewer server
(see The sync server). It streams the others' changes into your document, pushes
yours about once a second, reconnects on its own and tells you who else is there. It is the same
client as the web SDK's @nexdevit/nexpdf-web/sync and uses the global fetch of Node.js 18 and
later. Use it for a bot, a back-end service or a CLI that takes part in a document with the people
in the viewer.
It talks WebSocket (/api/sync/ws) first, with the global WebSocket of Node.js 22 and later (or
the WebSocket option). If there is none, or the socket never reaches the server's hello (a proxy
that does not pass upgrades, a refused token), it uses Server-Sent Events plus POST for the rest
of the session. transport: 'websocket' or 'sse' forces one.
import { PdfDocument } from '@nexdevit/nexpdf-node';
import { NexPdfSync } from '@nexdevit/nexpdf-node/sync';
const base = 'https://pdf.example.com/s/8f3c2a'; // the server, or a session URL
const token = process.env.NEXPDF_SESSION_TOKEN;
// Every copy starts from the server's document.
const res = await fetch(`${base}/api/sync/document`, { headers: { Authorization: `Bearer ${token}` } });
let doc = PdfDocument.fromBytes(new Uint8Array(await res.arrayBuffer()));
const sync = new NexPdfSync(doc, {
url: base,
token,
name: 'Review bot',
color: '#16A34A',
since: Number(res.headers.get('X-Sync-Seq')) || 0,
});
sync.on('remote', (report, changes) => console.log('applied', report.applied.length, 'changes'));
sync.on('presence', (peers) => console.log(peers.map((p) => p.name)));
sync.on('status', (status) => console.log('sync', status)); // connecting, online, offline, closed
sync.on('error', (e) => console.warn('sync', e));
await sync.connect(); // resolves when the server says hello
doc.addAnnotation({ page: 0, kind: 'Text', contents: 'Checked by the bot', rect: [520, 760, 540, 780] });
await sync.flush(); // or let the timer push itnew NexPdfSync(doc, options) takes a PdfDocument (or its doc.raw) and sets the document's
client id at once.
Options
| Option | Default | Meaning |
|---|---|---|
url | required | Server base URL: https://host (local mode) or https://host/s/<session id> |
clientId | random | Stable id of this device or tab: 1 to 64 characters of A-Z a-z 0-9 - _ . : @ |
name | Shown to the others (the server uses the token's name when it has one) | |
color | #RRGGBB for this person's cursor and selection | |
token | Session token, sent as Authorization: Bearer | |
since | 0 | Server sequence to catch up from (a previous seq); 0 is everything |
flushInterval | 1000 | How often local edits are looked for and pushed, in ms. 0 pushes only on flush() |
reconnectDelay | 1000 | First reconnect delay in ms; it doubles up to 30 s |
fetch | globalThis.fetch | The fetch to use (tests, proxies, a client with custom TLS settings) |
transport | auto | auto (WebSocket, else SSE + POST), websocket or sse |
WebSocket | the global one | The WebSocket class to use, for Node.js versions without a global one; null means none, SSE only |
credentials | Browser credentials mode; not needed in Node.js, where you pass token |
Events
sync.on(event, handler) adds a handler and returns a function that removes it.
| Event | Handler arguments | When |
|---|---|---|
remote | (report, changes) | A batch from the server was applied. report is the engine's apply report, changes the change set without your own echoes |
pushed | (result) | Your changes were accepted: ok, seq, applied, ignored, conflicts, errors |
conflict | (conflicts) | An apply or push reported conflicts. They are informational: the merge is already decided |
presence | (peers) | The people in the document changed. Each peer has client, name, color, page, cursor ({x, y} in PDF points, or null) and user; you are left out |
status | (status) | connecting, online, offline (waiting to reconnect) or closed |
reload | (seq) | The server's document was replaced: download it again and attach it |
error | (error) | A socket, stream, push or handler failed, or the server sent an error event. The client keeps going unless the server answered 401, 402, 403 or 404 |
Methods and properties
| Member | Does |
|---|---|
connect() | Opens the WebSocket (or the event stream) and starts the push timer. Resolves once the server said hello; rejects, and closes the client, when the server answers 401, 402, 403 or 404 (bad token, read-only, unlicensed, no such session). Other failures reconnect with backoff |
flush() | Pushes the local changes made since the last push, over the socket when it is open. Resolves to the push result, or null when there was nothing to send; throws when the server refuses the push |
setPresence({ page, cursor }) | Shares the page this person is on and a cursor in PDF points (null hides it) |
downloadDocument() | The server's current document as a Uint8Array, and updates seq from the X-Sync-Seq header |
attach(doc) | Switches to another document, for example one reopened after reload |
close() | Stops syncing. Edits not pushed yet stay in the document: call flush() first to send them |
clientId, seq, pushedClock, peers, status, transport | This copy's id, the last server sequence seen (pass it as since to resume), the clock of the last successful push, the other people, the connection status, and websocket or sse (null when not connected) |
Pushes and applies run one at a time, so a remote batch never lands in the middle of a push.
Presence and reload
await sync.setPresence({ page: 2, cursor: null }); // shows "Review bot" on page 3
sync.on('reload', async () => {
const bytes = await sync.downloadDocument();
doc.close();
doc = PdfDocument.fromBytes(bytes);
sync.attach(doc);
});
process.on('SIGTERM', async () => {
await sync.flush().catch(() => {});
sync.close();
doc.close();
});A viewer (read-only) session may stream and send presence, but its pushes are refused: flush()
throws and the timer reports error. Engine calls are synchronous; a large remote batch is applied
on the event loop, like any other call.
Exchange changes
The client is built on five document calls on doc.raw. Use them directly for another transport,
or to sync two documents in one process:
const a = await PdfDocument.open('shared.pdf');
const b = await PdfDocument.open('shared.pdf');
a.raw.syncSetClientId('alice');
b.raw.syncSetClientId('bob');
a.addAnnotation({ page: 0, kind: 'Highlight', color: '#FFD400', rect: [72, 700, 300, 716] });
const changes = a.raw.syncExportLocalJson(0); // what alice pushes
const report = JSON.parse(b.raw.syncApplyJson(changes));
console.log(report.applied, report.ignored, report.conflicts);
const since = JSON.parse(changes).clock; // pass it next time| Call | Returns |
|---|---|
syncSetClientId(id) | Sets the id this copy versions its changes under (1 to 64 characters of A-Z a-z 0-9 - _ . : @). Random when not set |
syncExportLocalJson(since) | Only this copy's own changes with a clock above since: what a client sends. Keep the returned clock for the next call |
syncExportJson(since) | Every change above since, from any client |
syncApplyJson(changes) | Applies a change set and returns a report |
syncSnapshotJson() | Every record with its version, base records and tombstones included |
Every copy must start from the same file. Records that exist when a document is first synced get the base version and are not sent as changes.
How changes merge
Each record carries a version {"lamport", "client"}, and every property of a record has its
own version. On apply, the higher version wins per property (last writer wins): a higher Lamport
clock, then the higher client id, so every copy picks the same winner in whatever order changes
arrive. Some keys merge as one property: an annotation's geometry, a page's content and resources,
a bookmark's parent and order. So Alice changing an annotation's text while Bob moves it keeps both
edits; two people changing the same property keep the later one.
When a merge combines properties from different writers, the appearance is redrawn the same way on every copy, for every annotation kind the engine creates. Deletion is a version too: an edit newer than the deletion brings the record back with all its properties.
The apply report has ok, clock, applied and ignored (changes that lost to a newer local
version) ids, conflicts (id, winner, local, remote, and the props that met a concurrent
edit), which are informational because the
merge is already decided, and errors for single records that could not be written. A malformed
change set fails as a whole.
The sync server
The NexPDF web viewer server hosts a sync endpoint. Clients download the document, stream the others' changes and push their own:
| Endpoint | Use |
|---|---|
GET /api/sync/document | The PDF to start from (header X-Sync-Seq) |
GET /api/sync/ws?since=<seq>&client=<id>&name=&color= | WebSocket, subprotocol nexpdf-sync (and bearer.<token> for a token): the stream's events plus pushed and error; the client sends push and presence messages |
GET /api/sync/stream?since=<seq>&client=<id> | Server-Sent Events: hello, changes, presence, reload |
POST /api/sync/push | A change set of the client's own changes |
POST /api/sync/presence | Name, colour, page and cursor of this client |
GET /api/sync/changes?since=<seq> | Catch-up as JSON, for polling |
GET /api/sync/snapshot | Every record and version |
Each request sends X-Client: <client id> and, outside a browser session, a session token as
Authorization: Bearer. Viewers may stream; only editors may push. Edits made in the
browser viewer itself, page operations and undo and redo included, reach the
other copies as changes from client server. hello reports the transport and the format.
The same client runs in the browser as @nexdevit/nexpdf-web/sync.
The server appends every accepted record to <data dir>/sync/<key>/changes.jsonl, next to the base
document, and a restarted server rebuilds the document from both. The data directory is
NEXPDF_DATA_DIR (off, none or memory keep everything in memory), else a per-user folder. A
changes batch with reset: true means the server's log restarted and the batch is the full
state.
Limits
- Attachments are not records and are not synced.
- Replacing the document on the server sends
reload: download it again andattachit.