Skip to main content

Server-side editing with @lexical/y

warning

@lexical/y is experimental. Its document layout and these APIs may change without a migration.

@lexical/y/headless runs Lexical edits on a stored Yjs 14 (@y/y) state on a server, without a DOM. It binds a headless editor with the same binding as the clients, so what the server writes is what a client would have written, and it merges with the clients' concurrent edits like any other peer's. See Yjs 14 (@lexical/y) for the binding itself.

import {editYState, readYState, seedYState} from '@lexical/y/headless';
import {
$createParagraphNode,
$createTextNode,
$getEditor,
$getRoot,
} from 'lexical';

// The clients' extensions (or `nodes`): the server must register every node
// type the clients use.
const config = {extensions: [AppNodesExtension]};

// A new document. `$build` starts from an empty root.
const state = seedYState(config, () => {
$getRoot().append($createParagraphNode().append($createTextNode('Hello')));
});

// One edit on the stored state.
const {update, state: next} = editYState(state, config, () => {
$getRoot().append($createParagraphNode().append($createTextNode('More')));
});
// Send `update` to the connected clients and store `next`.

// Read the document at a state: its JSON, Markdown, plain text...
const json = readYState(next, config, () =>
$getEditor().getEditorState().toJSON(),
);

API​

All of these take a config with the editor's extensions (or nodes), and optionally:

  • root: the shared root's name (default 'lexical-y');
  • clientIDRange: the range of client ids the server writes with (see yrs compatibility);
  • onWarn(warning): every warning, as {code, message} (see Warnings);
  • selfCheck: the binding's check of its own writes (default: on in development, off in production).
FunctionReturns
seedYState(config, $build)The state of a new document holding what $build writes.
editYState(state, config, $edit, options?){update, state, warnings} after one edit.
readYState(state, config, $read)What $read returns. Nothing is written.
  • seedYState is the way to create a document's content outside a client: from a template, an import, or a converter (see Converting a @lexical/yjs document). It writes the content the way a client's initialize() does: with a client id derived from the content (53 bits, or 32 with clientIDRange: 'uint32'), and outside any undo history. Seeding identical content twice gives the same bytes, so two servers that seed it at once write one copy. Content with random parts, such as the ids an extension draws for new blocks, is not identical: seed a document once.

  • editYState runs $edit in one discrete editor update, then commits the updates it made listeners schedule (an extension giving new blocks ids), and returns the merged update of everything they wrote, or update: null when nothing changed, and state with the update merged in. The update includes what opening the document wrote (ids for blocks stored without one, repairs), because the edit may build on it. Options:

    • allowedRoots: the shared roots the update may write to (default: the layout root). An update that writes anywhere else, or that cannot be resolved, is refused.
    • transact(doc): writes to other shared types of the same document, such as an activity log, in the same update. Their roots must be allowed.
    • tag: the tags of the editor update.

    An error thrown by $edit is rethrown, and nothing is returned.

  • readYState discards what opening the document writes. See Store what opening writes.

The helpers throw a YHeadlessError with a code:

  • 'not-initialized': the state has no layout record yet; seed it first.
  • 'read-only': the binding cannot write the document, for example because it uses a newer layout or a node type the config does not register. The message has the reason.
  • 'foreign-roots': the update writes to a root that is not allowed.

Warnings​

Every warning is a {code, message} object (YHeadlessWarning). The helpers pass each one to config.onWarn (default: console.warn outside production, nothing in production), and editYState also returns them in warnings. A warning never refuses an edit, in any environment: refusing on a self-check mismatch would make development and production behave differently. Log them, or alert on them by code. The codes are stable (new ones may be added): the binding's codes (YWarningCode from @lexical/y) and two of the helpers' own.

CodeMeaning
'unsupported-layout'The document's layout is missing, newer or malformed, or an older layout's root has content: read only (the helper then throws 'read-only').
'unknown-node-types'The document has node types the config does not register: read only.
'storage-mismatch'The document stores a node type in a way the config's class cannot: read only.
'self-check'A write did not read back as the editor's content.
'recovered-read'A change could not be read; the editor was rebuilt from the document.
'recovered-write'A write failed; the binding rewrote the document from the editor (the document is still right).
'editor-warning'A warning the editor reported (Lexical or an extension), forwarded with its message.
'follow-ups-exhausted'The edit's listeners kept scheduling updates. The helpers commit up to 8 follow-up updates after each update; the rest are not part of the result. Usually an extension whose update listener always changes the document.

An edit costs about as much as reading the document: about 300 ms in total for a 10,000-paragraph document in Node 24 (development build), for an update of about 70 bytes. The cost grows linearly with the document.

Server patterns​

Store what opening writes​

Opening a document can write to it: an extension gives ids to blocks stored without one (BlockIdExtension does), or the binding repairs a shape left by concurrent edits. editYState includes those writes in its update. readYState reads them but does not store them, so a value assigned on open, such as a block id, differs from one read to the next. Before reading such values (to show a model the document's block ids, for example), store what opening writes once:

const {update, state: repaired} = editYState(state, config, () => {});
if (update !== null) {
// Store `repaired` and send `update` to the connected clients.
}
// Reads of `repaired` now agree.

One writer per document​

Run a document's server edits one after another, each on the latest stored state, and store each update before the next edit starts. editYState returns its input state with its own update merged in: two edits run at once from the same stored state each return a state without the other's update, and storing both loses one of them. (The updates themselves merge like any two peers' updates. If edits must run in parallel, merge each update into the latest stored state instead of storing the returned state.)

Clients' edits made while the server edits merge with the server's update in either order, including typing in a block the server changes.

Reject updates to old roots​

A tab still running a client of an older layout (the Yjs 13 bindings' root or root-v2) must not write into the document. Check every incoming client update before applying it with inspectUpdateRoots from @lexical/y/server, which has no editor dependencies:

import {DEFAULT_ROOT_NAME, inspectUpdateRoots} from '@lexical/y/server';

const {roots, unresolved} = inspectUpdateRoots(update, serverDoc);
if (unresolved > 0 || [...roots].some(root => root !== DEFAULT_ROOT_NAME)) {
// Refuse it (and close the connection, or ask the client to reload).
}

Pass the server's copy of the document so that items nested in existing types and deletions resolve. Add the roots of your own shared types (an activity log) to the check.

For the server's own edits, editYState runs the same check with allowedRoots.

Converting a @lexical/yjs document​

seedYState also converts a document stored with the @lexical/yjs layouts. Load the old document into an editor with @lexical/yjs, seed its content, and merge the seed into the stored Yjs 14 document. The seed only holds the @lexical/y root, so the old root is left as it was:

import {$parseSerializedNode, $getRoot} from 'lexical';
import {mergeUpdates} from '@y/y';

// `json`: the old editor's `getEditorState().toJSON()`.
const seed = seedYState(config, () => {
for (const child of json.root.children) {
$getRoot().append($parseSerializedNode(child));
}
});
const converted = mergeUpdates([stored, seed]);

Clients of @lexical/y then open the converted document. Edits that old clients make after the conversion are not carried over: reject them as above, and upgrade every client that opens the document at the same time.

yrs compatibility​

yrs (y-crdt) before 0.28 reads client ids as 32-bit numbers, while Yjs 14 draws 53-bit ones. When updates pass through such a relay or store (y-crdt 0.23, for example), keep every client id in 32 bits: clientIDRange: 'uint32' in the server's config, and on every client's YCollabExtension (or YBinding). The range applies when the binding starts, so create a client's awareness after that.

Otherwise the relay stores the server's update under a truncated id, and a client that received the update both directly and from the relay shows the server's content twice. yrs 0.28 handles 53-bit ids.