Skip to content
whoistyping.wtf

Tiptap + WhoIsTyping in React and Next.js

Last updated 22 November 2026. End-to-end setup for real-time collaborative editing in React or Next.js (App Router) using Tiptap v3, @hocuspocus/provider, server-minted HS256 JWTs and signed document webhooks—hosted in Nuremberg, Germany (EU), starting on the free tier (1 project, 5 documents and 5 concurrent connections).

1. Install the Tiptap and Hocuspocus packages

Create a project in your WhoIsTyping dashboard and copy its Document Server ID and Document Server Secret. Keep the secret strictly on your Next.js or Node server (for example in WHOISTYPING_DOCUMENT_SERVER_SECRET, never prefixed with NEXT_PUBLIC_). Then install Tiptap v3, the Yjs collaboration extensions, @hocuspocus/provider, and jose for JWT signing:

npm install @tiptap/react @tiptap/pm @tiptap/starter-kit \
  @tiptap/extension-collaboration @tiptap/extension-collaboration-caret \
  @hocuspocus/provider yjs jose

Two Tiptap v3 changes matter here: @tiptap/extension-collaboration-caret replaces the older collaboration-cursor package, and built-in undo/redo history is disabled via StarterKit.configure({ undoRedo: false }) so Yjs manages collaborative history per user.

2. Mint short-lived HS256 JWTs on your server

When a browser connects to wss://collab.whoistyping.wtf/<Document Server ID>, WhoIsTyping verifies the bearer token strictly with HS256 against your project's Document Server Secret and validates numeric exp (and optional nbf) claims. Add a Next.js App Router endpoint that checks whether the signed-in user may access the requested document before minting a short-lived token:

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

const secret = new TextEncoder().encode(process.env.WHOISTYPING_DOCUMENT_SERVER_SECRET!);
const docServerId = process.env.WHOISTYPING_DOCUMENT_SERVER_ID!;

export async function POST(req: Request) {
  const user = await requireAuthenticatedUser(req); // your session helper
  const { documentName } = (await req.json()) as { documentName: string };

  if (!documentName || !(await canUserEditDocument(user.id, documentName))) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const token = await new SignJWT({
    sub: user.id,
    allowedDocumentNames: [documentName],
  })
    .setProtectedHeader({ alg: "HS256" })
    .setIssuedAt()
    .setExpirationTime("15m")
    .sign(secret);

  return NextResponse.json({
    url: `wss://collab.whoistyping.wtf/${docServerId}`,
    token,
  });
}

Notice that the WebSocket URL puts your Document Server ID in the path as a single segment (wss://collab.whoistyping.wtf/your-doc-server-id). Query parameters do not identify a project on the collaboration server.

3. Build a React / Next.js collaborative editor component

In Next.js App Router and React 18/19 StrictMode, create the Y.Doc and HocuspocusProvider inside useEffect, clean both up on unmount, and pass immediatelyRender: false to useEditor to avoid hydration mismatches:

// components/CollaborativeEditor.tsx
"use client";

import { useEffect, useState } from "react";
import * as Y from "yjs";
import { HocuspocusProvider } from "@hocuspocus/provider";
import { EditorContent, useEditor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Collaboration from "@tiptap/extension-collaboration";
import CollaborationCaret from "@tiptap/extension-collaboration-caret";

type Props = {
  documentName: string;
  websocketUrl: string;
  user: { name: string; color: string };
};

type Session = {
  ydoc: Y.Doc;
  provider: HocuspocusProvider;
};

export function CollaborativeEditor({ documentName, websocketUrl, user }: Props) {
  const [session, setSession] = useState<Session | null>(null);

  useEffect(() => {
    const ydoc = new Y.Doc();
    const provider = new HocuspocusProvider({
      url: websocketUrl,
      name: documentName,
      document: ydoc,
      sessionAwareness: false,
      token: async () => {
        const res = await fetch("/api/collab-token", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ documentName }),
        });
        if (!res.ok) throw new Error("Unable to authorize collaboration session");
        const data = (await res.json()) as { token: string };
        return data.token;
      },
    });

    setSession({ ydoc, provider });

    return () => {
      setSession(null);
      provider.destroy();
      ydoc.destroy();
    };
  }, [documentName, websocketUrl]);

  if (!session) return <p>Connecting editor...</p>;

  return <EditorSurface ydoc={session.ydoc} provider={session.provider} user={user} />;
}

function EditorSurface({
  ydoc,
  provider,
  user,
}: Session & { user: Props["user"] }) {
  const editor = useEditor({
    immediatelyRender: false,
    extensions: [
      StarterKit.configure({ undoRedo: false }),
      Collaboration.configure({ document: ydoc }),
      CollaborationCaret.configure({ provider, user }),
    ],
  });

  return <EditorContent editor={editor} />;
}

Important for @hocuspocus/provider v4+: pass sessionAwareness: false. In v4 of the client library, sessionAwareness defaults to true and encodes a null-delimited session ID alongside the document name, whereas WhoIsTyping runs Hocuspocus v3 on the server. Setting sessionAwareness: false keeps protocol framing compatible.

4. Style collaborator carets and name badges

CollaborationCaret renders remote cursors with .collaboration-carets__caret and collaborator labels with .collaboration-carets__label. Add these styles to your global CSS so remote cursors and name pills appear cleanly above text lines:

.tiptap .collaboration-carets__caret {
  border-left: 1px solid #0d0d0d;
  border-right: 1px solid #0d0d0d;
  margin-left: -1px;
  margin-right: -1px;
  pointer-events: none;
  position: relative;
  word-break: normal;
}

.tiptap .collaboration-carets__label {
  border-radius: 3px 3px 3px 0;
  color: #0d0d0d;
  font-size: 12px;
  font-style: normal;
  font-weight: 600;
  left: -1px;
  line-height: normal;
  padding: 0.1rem 0.3rem;
  position: absolute;
  top: -1.4em;
  user-select: none;
  white-space: nowrap;
}

5. Document names, authorization and plan limits

  • Use stable, scoped document names: pass a deterministic room key such as org-42-doc-981 (match across all collaborators on that document).
  • Authorize before minting a JWT: document names are routing identifiers. Anyone holding a valid project JWT can open any document name they know unless your backend restricts token issuance and validates claims.
  • Expiration behavior: exp is enforced when opening a WebSocket or reconnecting, not as a live mid-session disconnect timer. Revoke user access cleanly by stopping token issuance on reconnect and removing stale editors in your UI.
  • Stay within active document quotas: once your database persists snapshots via webhook, delete finished rooms with DELETE /api/v1/documents/{id} or enable automatic eviction of idle documents in project settings.

6. Persist snapshots with signed webhooks

Every WhoIsTyping plan—including Free (1 project, 5 documents and 5 concurrent connections)—includes document webhooks. In your project settings, set your webhook endpoint URL, switch the webhook format to hocuspocus_compatible, and choose the standard HTML preset (or off to receive Tiptap JSON only).

Deliveries use event: "change", coalesce rapid keystrokes into clean snapshots, retry up to 20 times on transient failures, and sign the raw request body with X-Hocuspocus-Signature-256: sha256=<hex> using your project's Webhook Secret:

// app/api/webhooks/whoistyping/route.ts
import { createHmac, timingSafeEqual } from "node:crypto";
import { NextResponse } from "next/server";

export async function POST(req: Request) {
  const rawBody = await req.text();
  const signature = req.headers.get("x-hocuspocus-signature-256") ?? "";
  const expected =
    "sha256=" +
    createHmac("sha256", process.env.WHOISTYPING_WEBHOOK_SECRET!)
      .update(rawBody)
      .digest("hex");

  const sigBuf = Buffer.from(signature);
  const expBuf = Buffer.from(expected);
  if (sigBuf.length !== expBuf.length || !timingSafeEqual(sigBuf, expBuf)) {
    return NextResponse.json({ error: "Invalid signature" }, { status: 401 });
  }

  const body = JSON.parse(rawBody) as {
    event: string;
    payload: {
      documentName: string;
      document: Record<string, unknown>;
      html?: Record<string, string>;
    };
  };

  if (body.event === "change") {
    await saveDocumentSnapshot({
      documentName: body.payload.documentName,
      json: body.payload.document.default,
      html: body.payload.html?.default ?? null,
    });
  }

  return NextResponse.json({ ok: true });
}

Security note: webhook HTML is rendered from Yjs with your chosen extension preset and is capped at 1 MiB, not sanitized. Always sanitize HTML before rendering it outside Tiptap (for example with DOMPurify).

7. Read or update live documents from your backend

Create a Content API Secret on your project to seed initial content, run server-side exports, or inject AI-generated edits straight into an open browser session without colliding with user cursors:

# Read the live Yjs document as HTML or JSON
curl -H "Authorization: Bearer $CONTENT_API_SECRET" \
  "https://whoistyping.wtf/api/v1/document-servers/$DOC_SERVER_ID/documents/org-42-doc-981?format=html"

# Upsert or replace live HTML in connected browsers
curl -X PATCH \
  -H "Authorization: Bearer $CONTENT_API_SECRET" \
  -H "Content-Type: application/json" \
  -d '{"html":"<p>Seeded from Next.js</p>"}' \
  "https://whoistyping.wtf/api/v1/document-servers/$DOC_SERVER_ID/documents/org-42-doc-981?format=html&upsert=1"

Related guides: Managed Hocuspocus vs self-hosting & Tiptap Cloud, whoistyping.wtf vs Tiptap Cloud, AI agents editing Tiptap docs via MCP, and Bubble collaborative setup.