快速开始

先运行双浏览器协同示例,再把最小 Client、Transport、Endpoint、Service 与 Adapter 组合迁入自己的应用。

本页包含两条路径。第一条路径运行官方示例,在两个浏览器中验证完整的协同链路;第二条路径说明最小的 Server 与 Web 组装方式,可复制到自己的 Univer 应用中。

开始之前,请先完成环境与版本要求。所有 @univerjs/* 与 @univerjs-pro/* package 都必须固定在同一个匹配的 release cohort 上,不能混用版本。

路径一:运行官方示例

运行前准备

本仓库要求 Node.js 24+,并声明使用 pnpm 10.32.1。请检查 node --version 与 pnpm --version 的输出,使用仓库自带的锁文件,并在仓库根目录下执行所有 pnpm example:* 命令。这些命令会构建浏览器端和服务端、检查示例的类型,然后启动服务,并不是热更新开发服务器;因此修改源码后需要停止进程并重新执行命令。

已有许可证时,请在执行命令前于终端设置 UNIVER_LICENSE 与 UNIVER_LICENSE_KEY。构建时 vite.config.ts 会把 UNIVER_LICENSE 写入浏览器产物,服务启动时 Collaboration SDK 会读取这两个变量。更换许可证后需重新执行命令。说明见许可证。

Bash
git clone https://github.com/dream-num/univer-collaboration-examples.gitcd univer-collaboration-examplespnpm install --frozen-lockfilepnpm example:quick-start

打开以下地址:

text
http://127.0.0.1:3010/?unit=quick-start-sheet

验证实时协同

  1. 在一个浏览器窗口中打开完整 URL。
  2. 在另一个浏览器窗口或标签页中打开同一 URL。
  3. 在任意一个窗口的 Sheet 中修改一个单元格。
  4. 确认另一个窗口中出现了同一处修改。

每个窗口都会建立自己的 WebSocket 会话。后续运行权限示例时,可以用独立的浏览器会话隔离两个账号的登录 Cookie。

这次成功证明了什么

text
Univer Collaboration Client  → Node Transport  → UniverCollabEndpoint  → UniverCollabService  → MemoryDatabaseAdapter

两个浏览器能够保持同步,说明整条路径都正常工作:每个浏览器都通过 HTTP 加载 Unit,使用一次性 Session Ticket 建立 WebSocket Session,并 JOIN 同一个 Room。随后 Service 执行 OT,确认新的 revision,通过 Adapter 保存,再由 Endpoint 广播给其他成员。

路径二:迁入自己的应用

以下是最小的 Server 与 Web 组装方式。完整的应用结构见官方 Quick Start:

如果已有 Univer Web 应用,请保留其 Runtime、Preset 和 UI,只添加下面这份 Collaboration Client 配置与 Server。如果从空项目开始,请把 Quick Start 目录中的 index.html、vite.config.ts 和样式文件复制过来,作为应用外壳。

按可运行文件迁入应用

请把 examples/quick-start 复制为初始骨架,并保留 package.json、index.html、vite.config.ts、web/styles.css、web/main.ts 和 server/main.ts。build 和 start 脚本需要在该目录中执行,因为 Express 会按工作目录查找 dist/web。请保留 Vite 中的许可证定义,并确保 #app 具有非零高度。下面的代码只说明这些部分如何组合;如需一个可运行的完整项目,请直接使用仓库中的文件。

示例中页面与 /universer-api 同源。如果前端部署到其他位置,需要把 HTTP 和 WebSocket Upgrade 都代理到后端,或者同时修改客户端的五个协议地址。unit 必须与后端创建的 ID 一致;仅在 URL 中写参数不会创建文档。示例读取 unit 后通过 loadSheetAsync() 显式加载。接入自己的应用时,请按协同集成的说明先设置当前用户,再执行加载。

1. 安装同一发布批次的 Package

服务端需要 Transport、Endpoint、Service 和一个 Database Adapter,浏览器端需要 Collaboration Client。请先安装这些 package,再把所有 Univer package 固定到同一个精确版本:

Bash
pnpm add \  @univerjs-pro/collaboration \  @univerjs-pro/collaboration-client \  @univerjs-pro/collaboration-client-ui \  @univerjs-pro/collaboration-database-memory \  @univerjs-pro/collaboration-endpoint \  @univerjs-pro/collaboration-service \  @univerjs-pro/collaboration-transport-node \  @univerjs-pro/license \  @univerjs/core \  @univerjs/preset-sheets-core \  @univerjs/presets \  @univerjs/protocol \  express react react-dom rxjs

当前需要安装哪些 package、精确到哪个版本,以官方示例的 manifest 为准,该文件本身即可运行。

2. 创建 Service、Endpoint 与初始 Unit

UniverCollabService 是协同的权威核心。Endpoint 把浏览器协议映射到 Service,Memory Adapter 则暂时负责保存 snapshot、changeset 和 revision:

TypeScript
import type { IWorkbookData } from "@univerjs/core";import { createServer } from "node:http";import express from "express";import { LocaleType } from "@univerjs/core";import { MemoryDatabaseAdapter } from "@univerjs-pro/collaboration-database-memory";import { UniverCollabEndpoint } from "@univerjs-pro/collaboration-endpoint";import { UniverCollabService } from "@univerjs-pro/collaboration-service";import { createNodeTransport } from "@univerjs-pro/collaboration-transport-node";import { ErrorCode, UniverType } from "@univerjs/protocol";const UNIT_ID = "quick-start-sheet";const unitData: IWorkbookData = {  id: UNIT_ID,  rev: 1,  name: "Quick Start Sheet",  appVersion: "",  locale: LocaleType.EN_US,  sheetOrder: ["sheet-1"],  sheets: {    "sheet-1": {      id: "sheet-1",      name: "Sheet 1",      rowCount: 100,      columnCount: 26,      cellData: {},    },  },  styles: {},  resources: [],};const database = new MemoryDatabaseAdapter();const service = new UniverCollabService({ dbAdapter: database });const endpoint = new UniverCollabEndpoint(service);const transport = createNodeTransport();transport.use(async (context, next) => {  context.userID = "demo-user";  await next();});transport.register(endpoint);await service.createUnitFromData(  { type: UniverType.UNIVER_SHEET, data: unitData },  { userID: "demo-user" },);

这里固定 demo-user,是为了展示可信身份如何从 Transport 传递到 Endpoint 和 Service。生产应用应在 transport.use() 中验证自己的 Cookie、Bearer token 或 Session,验证通过后再设置稳定的业务 userID。

3. 挂载授权、HTTP 与 WebSocket 入口

当前 Collaboration Client 会查询授权协议。Quick Start 对该接口的每次请求都返回 allowed: true,并把 Transport 挂载到应用的 HTTP Server 上:

TypeScript
const app = express();app.post("/universer-api/authz/-/object/-/batch_allowed", express.json(), (request, response) => {  const body = request.body as {    requests: Array<{ unitID: string; objectID: string; actions: unknown[] }>;  };  response.json({    error: { code: ErrorCode.OK, message: "" },    objectActions: body.requests.map((item) => ({      unitID: item.unitID,      objectID: item.objectID,      actions: item.actions.map((action) => ({ action, allowed: true })),    })),  });});app.use(express.static("dist/web"));const server = createServer(app);transport.attach(server);server.listen(3010, "127.0.0.1");

一律允许只是教学示例的简化做法,并不构成安全边界。正式应用必须保护 HTTP read、实时 JOIN、changeset submit 和 Unit 生命周期操作,完整的权限覆盖模型见身份与权限。

4. 在浏览器 Runtime 中注册 Collaboration Client

浏览器端沿用 Web SDK 和 Preset,再补充 Collaboration 的插件与协议地址:

插件配置

UniverLicensePlugin

  • license
    string
    客户端许可证文件的内容。

UniverCollaborationClientPlugin

  • socketService
    Ctor<ICollaborationSocketService>
    当前运行环境使用的 Socket 实现。
  • sendChangesetTimeout
    number默认值: 2000
    变更发出前的合批等待时间,单位毫秒。
  • authzUrl
    string默认值: '/universer-api/authz'
    检查权限的接口。
  • snapshotServerUrl
    string默认值: '/universer-api/snapshot'
    读取文档快照的接口。
  • collabSubmitChangesetUrl
    string默认值: '/universer-api/comb'
    提交变更集的接口。
  • collabWebSocketUrl
    string默认值: 'ws://127.0.0.1:8000/universer-api/comb/connect'
    同步实时变更的 WebSocket 地址。
  • wsSessionTicketUrl
    string默认值: '/universer-api/user/session-ticket'
    获取 WebSocket 会话票据的接口。

预设配置

UniverSheetsCorePreset

  • container
    string | HTMLElement默认值: 'app'
    编辑器挂载的元素,或该元素的 DOM ID。
TypeScript
import { LocaleType, LogLevel } from "@univerjs/core";import { UniverCollaborationPlugin } from "@univerjs-pro/collaboration";import { UniverCollaborationClientPlugin } from "@univerjs-pro/collaboration-client";import CollaborationClientEnUS from "@univerjs-pro/collaboration-client/locale/en-US";import {  BrowserCollaborationSocketService,  UniverCollaborationClientUIPlugin,} from "@univerjs-pro/collaboration-client-ui";import CollaborationClientUIEnUS from "@univerjs-pro/collaboration-client-ui/locale/en-US";import { UniverLicensePlugin } from "@univerjs-pro/license";import { UniverSheetsCorePreset } from "@univerjs/preset-sheets-core";import UniverPresetSheetsCoreEnUS from "@univerjs/preset-sheets-core/locales/en-US";import { createUniver, defaultTheme, mergeLocales } from "@univerjs/presets";import "@univerjs-pro/collaboration-client/facade";import "@univerjs/preset-sheets-core/lib/index.css";import "@univerjs-pro/collaboration-client-ui/lib/index.css";const httpProtocol = location.protocol === "https:" ? "https" : "http";const wsProtocol = location.protocol === "https:" ? "wss" : "ws";const baseURL = `${httpProtocol}://${location.host}/universer-api`;const unitId = new URLSearchParams(location.search).get("unit");if (!unitId) throw new Error("Open the URL printed by the server; it names the Sheet with ?unit=.");const { univerAPI } = createUniver({  locale: LocaleType.EN_US,  locales: {    [LocaleType.EN_US]: mergeLocales(      UniverPresetSheetsCoreEnUS,      CollaborationClientEnUS,      CollaborationClientUIEnUS,    ),  },  theme: defaultTheme,  logLevel: LogLevel.WARN,  collaboration: true,  presets: [UniverSheetsCorePreset({ container: "app" })],  plugins: [    [UniverLicensePlugin, { license: import.meta.env.UNIVER_LICENSE || undefined }],    UniverCollaborationPlugin,    [      UniverCollaborationClientPlugin,      {        socketService: BrowserCollaborationSocketService,        sendChangesetTimeout: 200,        authzUrl: `${baseURL}/authz`,        snapshotServerUrl: `${baseURL}/snapshot`,        collabSubmitChangesetUrl: `${baseURL}/comb`,        collabWebSocketUrl: `${wsProtocol}://${location.host}/universer-api/comb/connect`,        wsSessionTicketUrl: `${baseURL}/user/session-ticket`,      },    ],    UniverCollaborationClientUIPlugin,  ],});const workbook = await univerAPI.getCollaboration().loadSheetAsync(unitId);if (!workbook) throw new Error("Document could not be loaded");

页面中需要一个具有 id="app" 的元素,Unit 通过查询参数指定:

text
/?unit=quick-start-sheet

5. 用生产能力替换教学配置

教学配置接入应用时应替换为
固定 demo-user应用自身的认证 Middleware 和稳定用户 ID
权限默认允许覆盖 read、JOIN、submit 和生命周期操作的服务端 ACL
固定 Unit调用 createUnitFromData() 的应用创建 API 和产品记录
Memory AdapterSQLite 或通过契约测试的自定义持久化 Adapter

接下来阅读 Database Adapter 和身份与权限,再按需添加 History、Thread Comment、Worktree 或 Exchange。所有可运行的组装方式收录在示例索引中。

首次运行排查

现象检查项
安装或构建失败Node.js 24+、仓库声明的 pnpm 版本、Univer 包版本是否一致
3010 端口被占用停止前一个示例,或设置 PORT=3011,并在两个浏览器地址中都使用该端口
白屏或静态资源缺失构建是否完成、是否从示例目录启动、#app 是否具有高度
页面能打开但修改不同步两个窗口的完整 URL 是否相同;snapshot 与 session-ticket 请求是否成功;/universer-api/comb/connect 是否建立了 WebSocket 连接
重启后数据丢失Quick Start 使用内存存储;请继续运行 SQLite 示例

你觉得这篇文档如何?

© 2026 DreamNum Co., Ltd.