Getting ProseMirror state on the server

Using @liveblocks/node-prosemirror, it’s possible to retrieve the state of your ProseMirror document on the server.

Getting document state

To get your document state, you can use withProsemirrorDocument and api.getText.

import { Liveblocks } from "@liveblocks/node";import { withProsemirrorDocument } from "@liveblocks/node-prosemirror";
const liveblocks = new Liveblocks({ secret: "",});
const textContent = await withProsemirrorDocument( { roomId: "your-room-id", client: liveblocks, field: "prosemirror" }, async (api) => { return api.getText(); });
// "My content"console.log(textContent);

Modifying document state

To modify document state with transactions, use api.update. On the ProseMirror website you can find a full list of transforms and transactions functions.

import { Liveblocks } from "@liveblocks/node";import { withProsemirrorDocument } from "@liveblocks/node-prosemirror";
const liveblocks = new Liveblocks({ secret: "",});
await withProsemirrorDocument( { roomId: "your-room-id", client: liveblocks, field: "prosemirror" }, async (api) => { await api.update((_, tr) => { // Transaction example return tr.insertText("Hello world"); }); });

Using Yjs APIs instead

We don’t generally recommend it, but it’s also possible to use @liveblocks/node to retrieve the state of your ProseMirror document, and its Y.Doc, on the server. This may give you more control in some cases.

Using Liveblocks.getYjsDocumentAsBinaryUpdate you can fetch your Yjs data, and place it inside a Y.Doc. We can then call yDocToProseMirror from y-prosemirror to retrieve the ProseMirror editor’s state.

import * as Y from "yjs";import { Liveblocks } from "@liveblocks/node";import { yDocToProsemirrorJSON } from "y-prosemirror";
const liveblocks = new Liveblocks({ secret: "",});
export async function POST() { // Get your Yjs data as a binary update const update = await liveblocks.getYjsDocumentAsBinaryUpdate("my-room-name");
// Create a Yjs document const yDoc = new Y.Doc();
// Apply the binary update to `yDoc` Y.applyUpdate(yDoc, new Uint8Array(update));
// Get ProseMirror state from the default Yjs property it uses, "prosemirror" const prosemirrorState = yDocToProsemirrorJSON(yDoc, "prosemirror");
// { type: "doc", content: [{ type: "paragraph", content: [...] }] } console.log(prosemirrorState);}

If you’d like to edit your Y.Doc, make sure to read how to use your Y.Doc on the server.

We use cookies to collect data to improve your experience on our site. Read our Privacy Policy to learn more.