Skip to main content

Block IDs

Experimental

BlockIdExtension and BlockIdHTMLExtension are experimental. Their API may change in a minor release.

BlockIdExtension (from @lexical/extension) gives blocks stable, unique ids. Code outside the editor can then address a block by id, and the same id works wherever the document goes: in a headless process editing stored JSON, in a single-user editor, and between collaborators.

The main use case is editing by agents. An AI agent reads a document as a list of blocks with ids, and answers with operations such as "replace block b7", "insert after b7" or "delete b7". Those operations must find the right block even after the document was saved, reloaded, edited by someone else, or synchronized through a collaboration server.

Setup​

import {BlockIdExtension, buildEditorFromExtensions} from '@lexical/extension';
import {RichTextExtension} from '@lexical/rich-text';

const editor = buildEditorFromExtensions({
dependencies: [RichTextExtension, BlockIdExtension],
name: 'my-editor',
});

How ids are stored​

An id is NodeState under the key blockId (blockIdState). It is part of the node's JSON:

{
"type": "paragraph",
"$": {"blockId": "V1StGXR8_Z5jdHi6B-myT"},
"children": [...]
}

Because it is NodeState, an id:

  • round-trips through exportJSON/importJSON and the Lexical clipboard;
  • is kept when a node is cloned by an update, and restored by undo and redo;
  • is synchronized by any collaboration binding that synchronizes NodeState (@lexical/yjs v1 and v2 both do). Ids do not depend on the identity of items in a CRDT, so a document keeps its ids when it is exported from one collaboration session and imported into another, or edited without collaboration at all.

$copyNode does not copy the id (the state is declared with resetOnCopyNode), so a node split off another one starts without an id rather than with a duplicate.

Adopting blockIdState in an existing app​

blockId is the one key the extension reads and writes. An app that already stores its own block ids under $.blockId can switch to the extension without migrating documents: replace its own createState('blockId', ...) with the exported blockIdState (two state configs with the same key would both claim the same JSON field), and every stored id that is a non-empty string of at most 128 characters, such as a UUID, is adopted as it is. Only missing, invalid and duplicate ids are replaced.

Which blocks get ids​

By default, every element and decorator child of the root. Nested blocks are opt-in through $isIdentifiedBlock:

import {$defaultIsIdentifiedBlock, BlockIdExtension} from '@lexical/extension';
import {configExtension} from 'lexical';
import {$isListItemNode} from '@lexical/list';
import {$isTableCellNode} from '@lexical/table';

configExtension(BlockIdExtension, {
$isIdentifiedBlock: node =>
$defaultIsIdentifiedBlock(node) ||
$isListItemNode(node) ||
$isTableCellNode(node),
});

The predicate is evaluated when a node is marked dirty, so it should depend only on the node and its ancestors (a slot value's ancestors run through its host).

Blocks in slots​

Blocks inside slots get ids when the predicate identifies them, and everything the extension walks (the index, the repair of duplicates, removals of a host with its slots, the lookup while disabled) visits slot values as well as children. For example, to identify the blocks inside slot containers as well as the root's children:

import {$defaultIsIdentifiedBlock, BlockIdExtension} from '@lexical/extension';
import {$getSlotHost, $isElementNode, configExtension} from 'lexical';

configExtension(BlockIdExtension, {
$isIdentifiedBlock: node => {
if ($defaultIsIdentifiedBlock(node)) {
return true;
}
const parent = node.getParent();
return (
$isElementNode(node) &&
!node.isInline() &&
parent !== null &&
$getSlotHost(parent) !== null
);
},
});

Where the rules below speak of document order, a host's slot values (in its canonical slot order) come before its children, as $dfsWithSlots visits them. Replacing a slot value with $setSlot in one update keeps the replaced block's id, like replace.

Id format​

Ids are generated by generateId. The default, generateBlockId, makes 21 characters of the base64url alphabet (A–Z, a–z, 0–9, -, _): 126 random bits from crypto.getRandomValues, more than the 122 random bits of a version 4 UUID. There is no weaker fallback: where crypto.getRandomValues is missing (React Native without a polyfill, for instance), generateBlockId throws, so configure a generateId of your own there.

Ids are made by every collaborator and by servers that edit stored JSON, with no coordination between them. An id that is already in the editor is retried, but ids made concurrently by two peers cannot see each other, so the size alone has to make a collision practically impossible: with 126 bits, a document with a million blocks has less than a 10-26 chance of holding any two equal random ids. Shorter ids made unique by a per-peer prefix and a counter would need a prefix of about 72 bits anyway (peers have no shared identity outside a collaboration session, and their random prefixes collide too), would save only about 6 characters per block, and would make ids sequential: a model that mistypes …-17 as …-18 would silently edit another block, where a mistyped random id names no block and the edit fails visibly.

Any function that returns a non-empty string of at most 128 characters works. A replacement must stay unique across peers (for instance a per-peer prefix plus a counter); tests can inject a plain counter:

let n = 0;
configExtension(BlockIdExtension, {generateId: () => `b${++n}`});

If the ids are too long for a prompt, map them to short aliases (b1, b2, …) when building the prompt and back when applying the model's answer.

The format is fixed​

Readers are liberal and writers are fixed:

  • Read: any non-empty string of at most 128 characters is an id, so ids from other systems (UUIDs, an app's own ids) are adopted as they are.
  • Written: ids made by generateBlockId, and the positional ids described below, are always 21 characters of the base64url alphabet. Both kinds look alike on purpose: once stored, a positional id is an ordinary id, and nothing should treat it differently. The alphabet is also what HTML attributes, URLs and common id validators (/^[A-Za-z0-9_-]+$/) accept without escaping.

The derivation of positional ids is part of the stored format: every reader of a document stored without ids must derive the same ones, whatever version of Lexical it runs. It is specified exactly below, and pinned by tests.

When ids are assigned​

An identified block that has no id gets one in the same update that creates it, whether it was typed, pasted, or produced by importJSON, an HTML import or a markdown import. No later update is needed, so the first committed state that contains the block, and anything serialized from it, already carries the id.

Blocks created by edits get random ids from generateId. Blocks that a document loads without an id get positional ids instead (see the next section), so that everyone who loads the same document names them alike.

A document loaded without ids (for instance with editor.setEditorState(editor.parseEditorState(json))) gets them in the update that loads it. A document that is already in the editor when the extension is registered, or a state set with setEditorState from an editor without the extension, gets them in an update that runs right after.

Documents stored without ids​

A document stored before it had ids (written by an editor without the extension, by a server, or converted from another format) gets positional ids: derived from the document and from each block's place in it. Every reader and every collaborator that loads the same document derives the same ids, so:

  • Agents can read ids without writing first. Two reads of a document stored without ids name its blocks the same way, so an agent can put ids in a prompt and apply its answer to a later read, or to a collaborator's editor.
  • The ids an agent read stay valid once someone edits. The ids are stored the first time the document is written, and they are the ones every reader derived. A person's first edit (Enter at the start of a block, a type change) keeps them by the rules below, like any other id.
  • Concurrent first loads converge. Collaborators who open the same document at the same time assign the same ids, so their writes agree and nothing is left to repair when they meet.

What counts as a load:

  • a state set with setEditorState (parsed JSON, or a state from an editor without the extension), and the state of the editor when the extension is registered;
  • the first content an editor gets after the extension is registered: an initial state function, an import into a new headless editor, a collaboration binding's first sync;
  • a remote change that brings blocks without ids, or a repeated id: the collaborators who receive it name those blocks alike.

Everything else is an edit, and the blocks it creates get random ids.

Which blocks get derived ids:

  • blocks without an id get positional ids, derived from the document and their place;
  • a block whose id an earlier block (in document order) already has gets a duplicate id, derived from that id and the block's ordinal among its later holders; the first holder keeps the id.

Blocks that already have their own id keep it. A derived id never takes an id that another block already has: the next attempt is derived instead.

How positional ids are derived​

  1. The document key. Export the document in the compact JSON form (editorState.toJSON(true)), remove every blockId from the nodes' NodeState (and the $ that held only that), and write it as canonical JSON: JSON.stringify with no whitespace, of a copy in which every object's keys were inserted in UTF-16 code unit order (ECMAScript then writes keys that are array indices first, in numeric order). The key is the SHA-256 of its UTF-8 bytes. Ids are left out, so naming the blocks does not change the key.
  2. The block's place. A block's path among identified blocks: its index among the identified blocks with the same nearest identified ancestor (or the root), in document order (a host's slot values, in canonical slot order, before its children), after the path of that ancestor, joined by .. With the default predicate it is simply the block's index among the root's children: "0", "1", …; with list items identified, the second item of a list at index 3 is "3.1". The n-th retry after a collision appends #n ("3#1").
  3. The id. The first 21 characters of the unpadded base64url encoding of SHA-256(key ‖ UTF-8(place)): 126 bits.

Duplicate ids: the k-th later holder of the repeated id id (in document order, counting from 1 after the holder that keeps it) gets the first 21 characters of the unpadded base64url encoding of SHA-256(UTF-8("dup" + U+0000 + id + U+0000 + k)), with k in decimal and #n appended to it for the n-th retry after a collision ("1#1"). Repeated ids are retried in the code unit order of the ids. A duplicate id does not depend on the rest of the document, so renaming a duplicate costs the same whatever the document's size.

The key makes blocks at the same place in two different documents, or in two versions of the same document, get different ids. Two documents with exactly the same content (two new documents that only hold the default empty paragraph, for instance) do get the same ids: ids are unique within a document, so if you index ids across documents, key the index by document too.

The key is computed from the nodes' compact JSON, so readers must export the document the same way: register the same nodes on every reader, as collaboration already requires. A node class whose compact JSON changes (a new property whose value is not its default, for instance) changes the key of documents that contain it; readers on both sides of such a change derive different ids until the document is first written, after which the stored ids are used.

The derivation is not a secret and not meant to resist attacks; it only has to be deterministic and wide enough not to collide. The cost of positional ids is one pass over the document, only when blocks without an id appear: about 50 ms for the document key of a 10,000-block document in Node 24 (development build). A document stored with all its ids skips it, and so does the repair of a duplicate.

Updates that do not run transforms are repaired by a follow-up update that runs right after their commit. That is how changes from collaborators are handled: the collaboration bindings apply remote changes without transforms, and they do not write changes made during those updates back to the shared document.

Uniqueness: the existing block keeps the id​

When several identified blocks carry the same id, one keeps it and the others get fresh ids. Duplicates come from pasting copied content, duplicating a block, importing JSON or HTML that contains copies, or concurrent edits. The block that keeps the id is chosen in two steps:

  1. A block that already had the id before the update keeps it. A block that got the id in this update (a pasted or duplicated block, an imported one, a block whose id was set explicitly) yields and gets a fresh id. A reference held by an agent never jumps to a copy, wherever the copy is placed, even above the original.
  2. Between blocks that all had the id before, the earliest in document order keeps it. This settles duplicates that no single update created, such as copies that collaborators made concurrently and that only meet when their edits merge. Every collaborator that sees such a duplicate repairs it, so the rule must give all of them the same answer: it depends only on the document.
  3. Between blocks that all got the id in this update, the first one created keeps it (for instance the first of two copies imported together). Only the editor that makes this update decides, and the others receive the result, so creation order (Lexical's node keys, which only increase) is enough and cheap. In a load, which everyone must decide alike, the first in document order keeps it, and the others get duplicate ids.

Telling these apart costs nothing extra: the extension compares each holder with its own version in the previous editor state. Node keys cannot replace document order in rule 2: each collaborator numbers the nodes it receives in its own order, so with key order every collaborator would keep its own copy and give the other copy a fresh id, and the merged document would lose the id altogether.

Cut and paste moves the id: once the cut has removed the original, nothing else carries the id, so the pasted block keeps it.

The tie-break depends only on the document, not on which collaborator made a copy. Collaborators who see the same merged duplicate repair it the same way: all keep the earliest block and give the later one the duplicate id derived from the repeated id and its ordinal (see How positional ids are derived), so their repairs write the same value, at a cost that does not depend on the size of the document. (If they repair different states, the shared document settles on one value, as it is one NodeState value.) Once the ids are unique there is nothing left to repair. A repair never produces a new duplicate, so it cannot oscillate. A copy made locally never reaches the shared document as a duplicate at all, because it is repaired in the update that creates it.

Splits, joins, type changes and moves​

The ids follow the content the user sees:

EditResult
Enter in the middle or at the end of a blockThe block keeps its id; the new block after it gets a fresh one
Enter at the start of a blockThe text moves into the new block below, and the id moves with it; the empty block left above gets a fresh id
Backspace at the start of a block (join)The block that absorbs the content keeps its id; the removed block's id is gone
Paragraph to heading, quote or list ($setBlocksType, INSERT_*_LIST_COMMAND), and backThe new block keeps the id of the block it replaced
node.replace(newNode) with a new node that has no idThe new node keeps the replaced node's id
Moving a block (drag and drop, insertAfter/insertBefore of an existing node)The id moves with the block
Copy and paste, duplicate, JSON or HTML import of copied contentThe copy keeps the id only if no other block has it; otherwise the copy gets a fresh id and the original keeps it, even when the copy is placed above it
Cut and pasteThe pasted block keeps the id, since the cut removed the original
Undo and redoIds are restored exactly

Lexical's core does not carry NodeState across a type change: $setBlocksType creates a new element and calls replace. The extension recognizes these cases from the previous editor state, in the update that makes them: a new block that took over the children of a removed block, or that sits exactly where a removed block sat, takes over that block's id. A new block that took all the children of a block that is now empty takes its id too (Enter at the start). No core behavior is changed.

With nested ids, the same rules apply inside lists and tables. For example, Enter in a list item creates a new list item (with $copyNode, so without an id) and the rules above decide which item keeps the id. Converting paragraphs to a list gives the list items the paragraphs' ids, because they took over the paragraphs' content.

Looking blocks up​

import {$getBlockById, $getBlockId} from '@lexical/extension';

editor.read(() => {
const block = $getBlockById('b7');
const id = block && $getBlockId(block);
});

$getBlockById uses an index that the extension keeps up to date from the dirty nodes of each update, so its cost does not grow with the document. Every result is checked against the active state, so it never returns a removed or re-keyed block. A block created earlier in the same update is found once that update has committed.

Headless: assign ids in one write​

A server that stores Lexical JSON can assign ids to a document (or to whatever blocks lack one) in a single synchronous load-and-save:

import {BlockIdExtension, buildEditorFromExtensions} from '@lexical/extension';
import {RichTextExtension} from '@lexical/rich-text';

const editor = buildEditorFromExtensions({
$initialEditorState: null,
dependencies: [RichTextExtension, BlockIdExtension],
name: 'docs-pipeline',
});

// Parsing marks every node dirty, so this one commit assigns every missing
// id and repairs every duplicate.
editor.setEditorState(editor.parseEditorState(storedJSON));
const withIds = JSON.stringify(editor.getEditorState().toJSON());

Register the same nodes as the editors that wrote the document. Ids already in the document are kept, so running this again changes nothing. The ids it assigns are positional, so they are the same whether or not you store the result: a server that only reads (to show a model the document's block ids) does not need to write first.

How agents use this​

Give the agent each block's id and content, then apply its operations by id in one update:

import {$getBlockById, $getBlockId, blockIdState} from '@lexical/extension';
import {$convertFromMarkdownString} from '@lexical/markdown';
import {$getRoot, $setState} from 'lexical';

// 1. What the agent reads.
const blocks = editor.read(() =>
$getRoot()
.getChildren()
.map(node => ({id: $getBlockId(node), text: node.getTextContent()})),
);

// 2. What the agent answers, e.g.
// [{op: 'replace', id: 'b7', text: 'New text'},
// {op: 'insertAfter', id: 'b7', text: 'Another paragraph'},
// {op: 'delete', id: 'b9'}]
editor.update(
() => {
for (const op of ops) {
const block = $getBlockById(op.id);
if (block === null) {
continue; // Deleted meanwhile: report it back to the agent.
}
if (op.op === 'delete') {
block.remove();
} else {
const node = $createParagraphNode().append($createTextNode(op.text));
if (op.op === 'replace') {
// Takes the place of the old block, so it keeps id b7.
block.replace(node);
} else {
block.insertAfter(node); // Gets a fresh id in this update.
}
}
}
},
{discrete: true},
);

replace with a node that has no id keeps the replaced block's id, so the agent can keep referring to b7. A replace_block operation is therefore one line: $getBlockById(id)?.replace(newBlock). That holds on every binding. Whether a collaborator's concurrent typing in the replaced block survives is up to the binding: @lexical/y keeps it, @lexical/yjs v2 keeps it when the new block has the same type, and @lexical/yjs v1 drops it. To give a new block an id of the agent's choosing, set it before inserting: $setState(node, blockIdState, 'b7-intro'). If another block already has that id, it keeps it and the new node gets a fresh id.

HTML​

Ids are not part of HTML by default. BlockIdHTMLExtension (from @lexical/html) opts in:

import {BlockIdHTMLExtension} from '@lexical/html';

buildEditorFromExtensions({
dependencies: [RichTextExtension, BlockIdHTMLExtension],
name: 'my-editor',
});
  • Export: every identified block's element gets a data-block-id attribute in $generateHtmlFromNodes and in copied HTML.
  • Import: HTML imported through DOMImportExtension (for example with ClipboardDOMImportExtension) reads data-block-id back. Imported ids are never trusted: they are validated like any other id and go through the uniqueness rule, so pasting HTML whose ids are already in the document gives the pasted blocks fresh ids. The legacy importDOM path does not read the attribute.

Set export: false or import: false in its config to use only one direction.

caution

The attribute changes exported HTML. Keep BlockIdHTMLExtension out of editors whose HTML export must be byte-for-byte deterministic (a strict HTML codec, snapshot comparisons, content hashing), or set export: false there.

Collaboration​

The extension works with any collaboration binding that synchronizes NodeState, and needs nothing from the binding beyond that:

  • The collaborator who creates a block assigns its id, and the others receive it; they do not assign anything themselves.
  • A collaborator who pastes or duplicates a block repairs the copy locally, in the same update, so the copy reaches the others with its own id.
  • Duplicates that only appear when concurrent edits merge (two people moving the same block at the same time, which a CRDT can turn into two copies) are repaired by every collaborator with the earliest-in-document-order rule, and converge.
  • Ids are random and long enough that ids made concurrently by different collaborators do not collide (see Id format).
  • A shared document written without ids (by clients without the extension) gets positional ids from the collaborators who open it with the extension. They all derive the same ids, also when several open it at the same time, so their writes agree and the merge leaves nothing to repair. Blocks that a client without the extension adds later are named the same way by everyone who receives them.
  • The first content an empty editor gets is a load, so two clients that create the same initial content (the default empty paragraph included) give it the same ids. A binding that merges identical initial content written by several clients at once can therefore do so: @lexical/y, which deduplicates deterministic initial content, writes it once.

Repairs are ordinary local edits. With @lexical/yjs, the Yjs undo manager can record a repair together with the user's last change, so undoing that change can also undo the repair; the repair then runs again, and since its ids are positional, it gives back the same ids when it repairs the same document.

Disabling​

disabled: true (or setting the disabled output signal) stops assigning, repairing and indexing ids. Ids already in the document are kept. While disabled, $getBlockById falls back to a scan of the document. Enabling the extension again assigns and repairs ids for the whole document in one update; blocks left without an id meanwhile get positional ids.