blockcn

Collaboration

Let several people edit one document in real time with Yjs and a Hocuspocus server.

The collaboration add-on syncs the document with Yjs, and shows presence avatars and the other users' carets. It is a client: point it at a Hocuspocus WebSocket server. The example backend serves one at ws://localhost:8001/collaboration.

Start a server

Follow Backend, or use any Hocuspocus server you already run.

Install

npx shadcn@latest add https://blockcn.com/r/collaboration.json

Wire it in

A collaborative editor is set up differently from a local one. Read the rules below before you change this example.

src/components/collaborative-editor.tsx
"use client";

import { useMemo, useState } from "react";
import { Editor } from "@/components/editor/Editor";
import { useEditor } from "@/components/editor/useEditor";
import { createEditorExtensions } from "@/editor-core/schema/extensions";
import { useCollaboration } from "@/components/editor/collaboration/useCollaboration";
import {
  createCollaborationExtensions,
  createRandomCollaborationUser,
} from "@/components/editor/collaboration/collaborationExtensions";
import { CollaborationPresence } from "@/components/editor/collaboration/CollaborationPresence";

const COLLAB_URL = "ws://localhost:8001/collaboration";

export function CollaborativeEditor({ room }: { room: string }) {
  const collaboration = useCollaboration({ url: COLLAB_URL, room });
  const [user] = useState(createRandomCollaborationUser);

  // The Y.Doc doesn't exist on the first render.
  if (!collaboration.session) return null;

  return (
    <Room
      room={room}
      user={user}
      session={collaboration.session}
      collaboration={collaboration}
    />
  );
}

function Room({
  room,
  user,
  session,
  collaboration,
}: {
  room: string;
  user: ReturnType<typeof createRandomCollaborationUser>;
  session: NonNullable<ReturnType<typeof useCollaboration>["session"]>;
  collaboration: ReturnType<typeof useCollaboration>;
}) {
  const extensions = useMemo(
    () => [
      ...createEditorExtensions({ history: false }),
      ...createCollaborationExtensions(session, user),
    ],
    [session, user],
  );
  // Read-only tokens can't edit, and a rejected token can't sync.
  const editable = !collaboration.readOnly && collaboration.connection !== "unauthorized";
  // Starter content for new rooms comes from the server (see "Starter content").
  const editor = useEditor({ extensions, content: "", editable });

  return (
    <Editor editor={editor}>
      <div className="mb-4 flex items-center gap-3">
        <CollaborationPresence
          session={session}
          status={collaboration.status}
          connection={collaboration.connection}
          readOnly={collaboration.readOnly}
        />
        <span className="text-xs text-muted-foreground">Room: {room}</span>
      </div>
      <Editor.Frame>
        <Editor.Content />
        <Editor.Chrome />
      </Editor.Frame>
      <Editor.Outline />
    </Editor>
  );
}

To add media, tables, the whiteboard or Ask AI, spread their extensions into the same useMemo list and pass their slash categories to createEditorExtensions, as on the blocks and Ask AI pages.

Pass editor to CollaborationPresence and a click on someone else's avatar scrolls to their caret and keeps following it. Typing in the editor, or Escape, stops following. An avatar fades after five minutes without a caret move (idleAfterMs). While someone else's caret is in a block, the bar can show {name} is editing {block}. useSyncStatus(collaboration) reports connecting, connected, offline, saving (with pendingChanges), or saved. SyncStatus renders that label.

useCollaboration({ offline: true }) loads y-indexeddb the first time and stores the room in this browser. Edits made while the socket is down stay in that store and merge with the server when the connection returns. Leave it off and nothing is written to IndexedDB.

Open it in two tabs

Read the room from the query string:

const room = new URLSearchParams(window.location.search).get("room");

return room ? <CollaborativeEditor room={room} /> : <BlockEditor />;

Open http://localhost:3000/?room=demo in two browser tabs. Both should show the same document, a presence avatar, and the other tab's caret.

The example server only accepts connections without a token when COLLAB_ALLOW_ANONYMOUS=true (the .env.example default). Otherwise, pass a token; see Authentication.

Rules that differ from a local editor

RuleWhy
createEditorExtensions({ history: false })Yjs brings its own undo/redo. Leaving the default history on logs a warning and conflicts with sync.
useEditor({ content: "" })If every client passed a starting document, each one would insert it again.
Seed new rooms on the serverThe server's seed hook fills a brand-new room once, even when several people open it at the same moment. Clients that each seed an empty room would insert the content twice.
Wait for collaboration.sessionThe Y.Doc and provider are created in an effect, so the session is null on the first render.

Starter content

A new room starts empty. To give it starter content, seed it on the server. createCollaboration({ seed }) takes a function (roomName) => docJSON | null. Hocuspocus calls it once, when a room with nothing in storage is first loaded, even when several clients connect at the same instant. It writes Tiptap JSON (what editor.getJSON() returns) into the room's Yjs document. The example server sets seed from COLLAB_SEED: demo uses the editor's demo document, and none (the default) leaves new rooms empty.

server
createCollaboration({
  storage,
  auth,
  seed: async (room) => (room.startsWith("template:") ? await loadTemplate(room) : null),
});

Without a server hook, useSeedCollaborativeContent(editor, collaboration, content) seeds from the client. It skips read-only clients and rooms that have been seeded before (it keeps a seeded flag in the document). Two clients that open a brand-new room at the same instant can both seed it, so use the server hook if you can.

Rooms and users

  • A room name is the document ID. Everyone in demo shares one document, and other is a different one. Use your own document IDs. The example server accepts 1-128 characters of letters, digits, _, -, . and : (for namespacing, like team-42:doc-7), starting with a letter or digit.
  • Replace createRandomCollaborationUser with the signed-in user: { name: string; color: string }. Use a hex color, which is used for their caret and selection.

Authentication

Your app's backend decides who may open which room and issues a short-lived token. The editor sends it with the connection, and the collaboration server checks it before loading the document.

const collaboration = useCollaboration({
  url: COLLAB_URL,
  room,
  // A function runs on every connect and reconnect, so it can fetch a fresh token.
  token: () => fetch(`/api/collab-token?room=${room}`).then((r) => r.text()),
  onAuthenticationFailed: (reason) => {
    // "missing-token", "invalid-token", "token-expired", "room-mismatch", "invalid-room", "server-misconfigured"
    if (reason === "token-expired") router.refresh();
  },
});

The example server expects an HS256 JWT signed with COLLAB_SECRET, with these claims:

ClaimValue
roomThe room name. A token opens only that room.
permission"write" to edit, or "read" for a read-only connection.
expRequired. Keep it short, e.g. 1 hour.
sub, nameOptional. Passed to server hooks in the connection context.

Mint it in your backend with any JWT library, for example jose:

src/app/api/collab-token/route.ts
import { SignJWT } from "jose";

export async function GET(req: Request) {
  const user = await getSignedInUser(req); // your auth
  const room = new URL(req.url).searchParams.get("room") ?? "";
  const permission = await canEdit(user, room) ? "write" : await canView(user, room) ? "read" : null;
  if (!permission) return new Response("Forbidden", { status: 403 });

  const token = await new SignJWT({ room, permission, name: user.name })
    .setProtectedHeader({ alg: "HS256" })
    .setSubject(user.id)
    .setExpirationTime("1h")
    .sign(new TextEncoder().encode(process.env.COLLAB_SECRET));
  return new Response(token);
}

For local testing, pnpm collab:token --room demo --permission read in server/ prints a token. The demo app reads one from ?token=…, then removes it from the address bar with history.replaceState and sends no Referer (<meta name="referrer" content="no-referrer">).

Don't put tokens in URLs in production: they end up in browser history, bookmarks, server logs and Referer headers. Fetch them from your own backend with the token function shown above.

A read-only connection still shows presence, but the server ignores its edits. useCollaboration sets readOnly; make the editor non-editable with it, as in the example above. A token is checked when the connection opens, and its exp keeps being enforced while the connection is open. About a minute before it expires, the server asks the client for a new one, which calls your token function again. If no valid token arrives, once exp passes the server closes that document's connection (not the whole WebSocket, which other documents may share) and reports token-expired. The client calls token again and re-authenticates on the same socket; a rejected token-expired is retried with fresh tokens twice before onAuthenticationFailed fires. Pass a function, not a string, so tokens can be refreshed. A user who loses access is disconnected no later than their token's expiry, so keep tokens short-lived (minutes, not days).

Connection status

useCollaboration returns connection, which CollaborationPresence shows next to the avatars:

connectionShownMeaning
connectingConnecting…First attempt.
connectedGreen dotLive.
reconnectingReconnecting…The connection dropped and the provider is retrying. Edits are kept and sync when it's back.
offlineOfflineThe browser has no network.
unauthorizedNo accessThe server rejected the token. See authError for the reason.

Pass readOnly to show a Read-only badge.

Deploy

  1. Set a secret and turn off anonymous access. Generate COLLAB_SECRET with openssl rand -base64 48, share it only with the backend that mints tokens, and remove COLLAB_ALLOW_ANONYMOUS.

  2. Pick storage. COLLAB_STORAGE=file writes one Yjs file per room to COLLAB_DATA_DIR. COLLAB_STORAGE=sqlite keeps every room in one SQLite file at COLLAB_SQLITE_PATH. Both need a persistent volume, and both suit one server process. To run several instances, add Hocuspocus's Redis extension and a shared database by implementing the Storage interface in server/src/collab/storage.ts.

  3. Proxy WebSockets. Behind nginx, forward the upgrade headers and raise the idle timeout:

    location /collaboration {
      proxy_pass http://127.0.0.1:8001;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "upgrade";
      proxy_read_timeout 1h;
    }

    Use wss:// in useCollaboration({ url }) once the page is served over HTTPS.

  4. Give shutdown time. On SIGTERM the server stops accepting connections, closes the open ones and waits for every pending document write, up to COLLAB_SHUTDOWN_TIMEOUT_MS (10 s). Set your platform's grace period longer than that, e.g. Kubernetes terminationGracePeriodSeconds: 15.

  5. Back up the data. Copy COLLAB_DATA_DIR, or use sqlite3 collab.sqlite ".backup backup.sqlite" for SQLite. Don't copy a live SQLite file directly.

See Backend for every variable.

Not included yet

Comments and threads, and version history snapshots, aren't part of the add-on or the example server.

On this page