Server

Server-side implementation of DocSync

DocSyncServer

Creates a DocSync server that handles WebSocket connections, authentication, authorization, and document synchronization.

import { DocSyncServer, PostgresProvider } from "@docukit/docsync/server";

const server = new DocSyncServer({
  port: 8080,
  docBinding,
  provider: PostgresProvider,
  async authenticate({ token }) {
    const user = await verifyToken(token);
    if (!user) return undefined;
    return { userId: user.id, context: { role: user.role } };
  },
  async authorize({ type, payload, userId, context }) {
    return true;
  },
});

Props

Prop

Type


authenticate

Called once per WebSocket connection attempt. Must validate the provided token and resolve the canonical userId.

async authenticate({ token }) {
  const user = await verifyToken(token);
  if (!user) return undefined;
  return {
    userId: user.id,
    context: { role: user.role, orgId: user.orgId },
  };
}

Props

Prop

Type

Returns

Prop

Type

Return undefined to reject the connection.


authorize

Called for each operation after authentication. Use this to implement fine-grained access control.

async authorize({ type, payload, userId, context }) {
  if (type === "sync-operations") {
    const { docId } = payload;
    return await canUserAccessDoc(userId, docId, context.orgId);
  }
  return true;
}

Props

Prop

Type

Returns

Return true to allow the operation, false to deny.


Events

onClientConnect

Called when a client successfully connects after authentication.

server.onClientConnect((event) => {
  console.log(`User ${event.userId} connected from device ${event.deviceId}`);
});

Prop

Type

onClientDisconnect

Called when a client disconnects.

server.onClientDisconnect((event) => {
  console.log(`User ${event.userId} disconnected: ${event.reason}`);
});

Prop

Type

onSyncRequest

Called after each sync-operations request completes. Follows "wide events" philosophy: one event per operation with all context.

server.onSyncRequest((event) => {
  console.log(
    `Sync ${event.status} for doc ${event.req.docId} in ${event.durationMs}ms`,
  );
});

Prop

Type


close

Closes the server and all connections.

await server.close();

On this page

Edit on GitHub