@syncfusion/ej2-collaborator-server
v35.2.12
Published
A Node.js WebSocket server for real-time collaborative editing with a pluggable `ICollaborationAdapter`, Redis-backed storage, and support for horizontal scaling. ---
Keywords
Readme
ej2-collaborator-server
A Node.js WebSocket server for real-time collaborative editing with a pluggable ICollaborationAdapter, Redis-backed storage, and support for horizontal scaling.
Overview of the Project
@syncfusion/ej2-collaborator-server is a transport-focused, control-agnostic
collaboration package. It owns the WebSocket surface, the per-room fan-out,
the background save queue, and the Redis-backed action/room/user services
that a Syncfusion editor (PDF Viewer and other controls that speak the
shared action envelope) talks to in real time. Control-specific behaviour
— action shape, operational transform, and persistence — is plugged in by
implementing ICollaborationAdapter in the consuming application.
Using this Package with an AI Coding Agent
Before generating Syncfusion code, ask your AI coding agent to run the Syncfusion setup using the following prompt:
Set up this project for Syncfusion before generating code. Fetch
and follow the official instructions at https://ai.syncfusion.com/,
then report the detected platform, installed skill pack, MCP
status, and any required licensing action.The setup detects your project’s platform and loads the appropriate Syncfusion skill pack. No Syncfusion account or MCP key is required to install or read Syncfusion agent skills.
Platform reference: https://ai.syncfusion.com/javascript/llms.txt
Integration Guidelines
A reference for teams adopting @syncfusion/ej2-collaborator-server for real-time
collaborative editing — currently framed around the PDF Viewer control,
with the same pattern available to any other control that consumes the
shared CollaborationAction envelope.
What is @syncfusion/ej2-collaborator-server?
@syncfusion/ej2-collaborator-server is a reusable, control-agnostic library that
handles all shared collaboration concerns so product teams don't
re-implement them:
Integration Workflow
- Install the package
npm install @syncfusion/ej2-collaborator-server - Create your adapter (e.g.
PdfViewerAdapter.js):- Extends
ICollaborationAdapterexported from this package. - Maps your control's native action ↔
CollaborationAction. - Plugs in your control's OT/transform routine inside
transformOperations. - Plugs in your control's save routine inside
processSaveRequestAsync(and optionallysaveOperationsAsync).
- Extends
- Create the server in your app entry point:
const { CollaborationServer } = require('@syncfusion/ej2-collaborator-server'); const PdfViewerAdapter = require('./adapters/PdfViewerAdapter'); const adapter = new PdfViewerAdapter({ serviceUrl: 'http://localhost:62870/' }); const server = new CollaborationServer({ port: 8080, redis: { host: '<redis-host>', port: 6380, username: 'default', password: '<redis-password>', tls: {} }, adapter, saveThreshold: 100 // operations between flushes }); server.app.get('/api/test', (_req, res) => res.json({ status: 'Node Server Running' })); server.start(); - Connect a client to
ws://<host>:<port>(the upgrade is mounted on the same HTTP server that hosts/api/collaboration/*) and send the supported frames (connectionId,JoinGroup,action,addUser,removeUser). - Call the REST endpoints under
/api/collaboration/*from your application when you need to add an operation, fetch pending operations, look up the effective pending version, or clear records.
Public API
The members below are what product teams call or implement. Everything else is internal to this package.
ICollaborationAdapter (base class — implemented by the consumer)
| Member | Purpose |
| --- | --- |
| mapControlToGenericAction(controlAction) | Pack a control action into the common CollaborationAction. |
| mapGenericToControlAction(collaborationAction) | Unpack a common CollaborationAction into the control action shape. |
| transformOperations(actions) | Run your control's OT over a batch of actions. Returns the transformed array. |
| processSaveRequestAsync(request) | Runs the actual save (called by DocumentSaveWorker). |
CollaborationServer (the package entry point)
| Member | Purpose |
| --- | --- |
| new CollaborationServer({ port, redis, adapter, saveThreshold? }) | Construct the server. The port can be overridden by process.env.PORT. |
| start() | Start the HTTP + WebSocket server, mount REST routes, and run the background save worker. |
| app | The underlying express.Express instance — attach product-specific routes (e.g. server.app.get('/api/test', ...)). |
| actionService | The ActionService instance wired for you; useful when mounting custom Edit-Control routes. |
ActionService
| Member | Purpose |
| --- | --- |
| addAction(roomName, action) | Persist a CollaborationAction and bump the room version. |
| getActions(roomName) | Fetch the current action list for a room. |
| addOperation(action, adapter) | Run the Lua-script flow: assign version, transform prior ops via adapter.transformOperations, persist, and enqueue a partial save when the threshold is reached. |
| getPendingOperations(roomName, startIndex, endIndex) | Fetch stored actions in a range. |
| getEffectivePendingVersion(roomName, startIndex) | Fetch newer-than-startIndex actions for a joining client. |
Configuration (constructor options)
| Property | Default | Purpose |
| --- | --- | --- |
| port | process.env.PORT or 8080 | HTTP/WS port. |
| redis | — | ioredis connection options (host, port, username, password, tls, ...). |
| adapter | — | The ICollaborationAdapter instance used by the save worker and REST controller. |
| saveThreshold | Helper.SAVE_THRESHOLD (100) | The save threshold (in actions) after which a pending save is flushed to the document. |
Getting Started
This section shows how a consumer application wires up and integrates
@syncfusion/ej2-collaborator-server with the PDF Viewer reference adapter.
1. Server Bootstrap
// server.js
const {
CollaborationServer
} = require('@syncfusion/ej2-collaborator-server');
const PdfViewerAdapter = require('./adapters/PdfViewerAdapter');
const adapter = new PdfViewerAdapter({
serviceUrl: 'http://localhost:62870/'
});
const server = new CollaborationServer({
port: 8080,
redis: {
host: '<redis-host>',
port: 6380,
username: 'default',
password: '<redis-password>',
tls: {}
},
adapter,
saveThreshold: 100
});
server.app.get('/api/test', (_req, res) => {
res.json({ status: 'Node Server Running' });
});
server.start();2. Adding Control-Specific Routes
The package's built-in REST routes (/api/collaboration/*) handle add/replay
of common CollaborationActions. Add control-specific routes to
server.app when you need them — for example, the seed-document route
that loads the PDF, replays pending annotations, and returns the URL.
// server.js (continued)
server.app.post('/api/PdfViewer/open', async (req, res) => {
try {
const { roomName, fileName } = req.body;
// TODO: load the seed PDF for `roomName` here.
const actions = await server.actionService.getPendingOperations(
roomName, 0, -1
);
// TODO: apply `actions` to the freshly loaded PDF.
res.json({ documentUrl: '', version: 0, actions });
} catch (e) {
console.error(e);
res.status(500).json({ error: e.message });
}
});3. Reference Adapter — PdfViewerAdapter.js
// adapters/PdfViewerAdapter.js
const {
ICollaborationAdapter
} = require('@syncfusion/ej2-collaborator-server');
class PdfViewerAdapter extends ICollaborationAdapter {
constructor(options = {}) {
super();
this.serviceUrl = options.serviceUrl || 'http://localhost:62870/';
}
mapGenericToControlAction(collaborationAction) {
return {
roomName: collaborationAction.roomName,
connectionId: collaborationAction.connectionId,
currentUser: collaborationAction.currentUser,
version: collaborationAction.version,
clientVersion: collaborationAction.clientVersion,
isTransformed: collaborationAction.isTransformed,
annotations: collaborationAction.data
? JSON.parse(collaborationAction.data)
: []
};
}
async transformOperations(actions) {
// The PDF Viewer annotation shape is stable across versions so no
// per-control OT is required: mark each action as transformed.
//perform transform operations using your source code
actions.forEach(action => { action.isTransformed = true; });
return actions;
}
async processSaveRequestAsync(request) {
////perform save operations with the obtained actions and it is control specific
}
}
module.exports = PdfViewerAdapter;Reference – Consumer-Side Collaborative Editing Controller
The package exposes four built-in REST routes under /api/collaboration/*
(via registerRoutes), but most consumer apps also add their own surface
to bridge their editor's native action shape with the shared
CollaborationAction envelope. The component below is the standard
shape teams ship in this position. It lives in your application code,
not in this package.
controllers/collaborative-editing-controller.js
// controllers/collaborative-editing-controller.js
function registerCollaborativeEditingRoutes(app, actionService, adapter) {
app.post('/api/CollaborativeEditing/ImportFile', async (req, res) => {
try {
const { roomName, fileName } = req.body;
console.log('[ImportFile]', roomName, fileName);
const actions = await actionService.getPendingOperations(
roomName, 0, -1
);
// TODO:
// 1. Load the seed document for `roomName` / `fileName`.
// 2. Map stored `CollaborationAction`s back via
// `adapter.mapGenericToControlAction(...)`.
// 3. Replay them on the freshly loaded document.
// 4. Return the serialized payload.
res.json({ version: 0, sfdt: '', actions });
} catch (e) {
console.error(e);
res.status(500).json({ error: e.message });
}
});
app.post('/api/CollaborativeEditing/UpdateAction', async (req, res) => {
try {
const action = await actionService.addOperation(
req.body, adapter
);
res.json(adapter.mapGenericToControlAction(action));
} catch (e) {
console.error(e);
res.status(500).json({ error: e.message });
}
});
app.post('/api/CollaborativeEditing/GetActionsFromServer', async (req, res) => {
try {
const { roomName, version } = req.body;
const actions = await actionService.getEffectivePendingVersion(
roomName, version
);
res.json(
actions.map(x => adapter.mapGenericToControlAction(x))
);
} catch (e) {
console.error(e);
res.status(500).json({ error: e.message });
}
});
}
module.exports = {
registerCollaborativeEditingRoutes
};Wiring the Controller
The function is meant to be called with server.actionService and the
adapter instance after CollaborationServer is constructed:
// server.js (continued)
const {
registerCollaborativeEditingRoutes
} = require('./controllers/collaborative-editing-controller');
require('cors')(); // if you need cross-origin; see snippet below for in-place use.
registerCollaborativeEditingRoutes(
server.app,
server.actionService,
adapter
);
server.start();Reference – PDF Viewer Adapter
A self-contained reference adapter for the Syncfusion PDF Viewer
control. The same shape applies to any other control that consumes the
shared CollaborationAction envelope — only the action type and the
serviceUrl change.
// adapters/PdfViewerAdapter.js
const { ICollaborationAdapter } = require('@syncfusion/ej2-collaborator-server');
class PdfViewerAdapter extends ICollaborationAdapter {
constructor(options = {}) {
super();
this.serviceUrl = options.serviceUrl || 'http://localhost:62870/';
}
mapGenericToControlAction(collaborationAction) {
return {
roomName: collaborationAction.roomName,
connectionId: collaborationAction.connectionId,
currentUser: collaborationAction.currentUser,
version: collaborationAction.version,
clientVersion: collaborationAction.clientVersion,
isTransformed: collaborationAction.isTransformed,
annotations: collaborationAction.data
? JSON.parse(collaborationAction.data)
: []
};
}
async transformOperations(actions) {
// For the PDF Viewer, annotation shape is stable across versions so
// there is no per-control OT to run. Pass the array through unchanged.
actions.forEach(action => { action.isTransformed = true; });
return actions;
}
async processSaveRequestAsync(request) {
// consumers typically POST to their own persistence endpoint here;
// for the PDF Viewer that's usually the existing viewer save URL.
const url = `${this.serviceUrl}/api/PdfViewer/ProcessSaveRequest`;
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request)
});
if (!response.ok) {
throw new Error(`ProcessSaveRequest failed : ${response.status}`);
}
}
}
module.exports = PdfViewerAdapter;Then construct the server using the PDF Viewer adapter:
// server.js
const { CollaborationServer } = require('@syncfusion/ej2-collaborator-server');
const PdfViewerAdapter = require('./adapters/PdfViewerAdapter');
const adapter = new PdfViewerAdapter({
serviceUrl: 'http://localhost:62870/'
});
const server = new CollaborationServer({
port: 8080,
redis: {
host: '<redis-host>',
port: 6380,
username: 'default',
password: '<redis-password>',
tls: {}
},
adapter,
saveThreshold: 100
});
server.start();