blockcn

Save and load content

Start from your own document, listen for changes, and persist them as JSON, HTML or Markdown.

useEditor accepts every Tiptap editor option. The useful ones for content are content (where to start) and onUpdate (what changed). With no content, the editor starts empty. Pass DEFAULT_EDITOR_CONTENT when you want the built-in demo document.

Start with your own content

content accepts Tiptap JSON or an HTML string.

const editor = useEditor({ extensions, content: "" });

Store JSON

Save documents as JSON (editor.getJSON()). It keeps every block exactly, including to-dos, tables and drawings. Use HTML or Markdown for display and export.

Listen for changes

const editor = useEditor({
  extensions,
  content: initialDoc,
  onUpdate: ({ editor }) => {
    const json = editor.getJSON();
    // save json
  },
});

onUpdate runs on every keystroke. When you save to a server, debounce it.

Example: autosave to an API

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

import { useEffect, useMemo, useRef } from "react";
import type { JSONContent } from "@tiptap/core";
import { Editor } from "@/components/editor/Editor";
import { useEditor } from "@/components/editor/useEditor";
import { createEditorExtensions } from "@/editor-core/schema/extensions";

const extensions = createEditorExtensions();

export function BlockEditor({ docId, initialDoc }: { docId: string; initialDoc: JSONContent }) {
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);

  const editor = useEditor({
    extensions,
    content: initialDoc,
    onUpdate: ({ editor }) => {
      clearTimeout(timer.current);
      timer.current = setTimeout(() => {
        fetch(`/api/docs/${docId}`, {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(editor.getJSON()),
        });
      }, 800);
    },
  });

  useEffect(() => () => clearTimeout(timer.current), []);

  return (
    <Editor editor={editor}>
      <Editor.Frame>
        <Editor.Content />
        <Editor.Chrome />
      </Editor.Frame>
    </Editor>
  );
}

Load initialDoc on the server or with your data-fetching library, and render BlockEditor once it's available. content is only read when the editor is created.

Read content on demand

useEditor returns the Tiptap Editor (or null before it mounts), so the standard methods work:

MethodReturns
editor.getJSON()The document as Tiptap JSON. Store this.
editor.getHTML()An HTML string.
editor.getText()Plain text, e.g. for search indexing.
editor.isEmptytrue when the document has no content.
editor.commands.setContent(doc)Replaces the document.
editor.commands.clearContent()Empties the document.

Convert to Markdown or standalone HTML

The export helpers from export-menu also work outside the export menu, for example to store a Markdown copy next to the JSON:

import { importHTML, importMarkdown } from "@/lib/export";
import { serializeMarkdown, serializeHtmlDocument, documentTitle } from "@/lib/export/serialize";

const doc = editor.getJSON();
const markdown = serializeMarkdown(doc, [], editor);
const html = serializeHtmlDocument(doc, documentTitle(doc), [], editor.schema);

importMarkdown(editor, markdown);
importHTML(editor, "<p>Hello</p>");

Excalidraw drawings appear as placeholders unless you pass rendered PNGs as the drawings argument: the second argument of serializeMarkdown, and the third of serializeHtmlDocument (after the title). collectDrawingDataUrls(doc) from @/lib/export/registry returns that list once the Excalidraw addon has registered its collector.

Select several blocks

Shift+Arrow at the start or end of a block, or Shift+click on a block handle, extends a block selection. The selected blocks are highlighted. Dragging in the gutter selects every block the pointer crosses.

The first Ctrl/Cmd+A selects the block the caret is in. The second selects every block. Escape does that second step when a block is already selected, and returns to a caret when every block is selected.

The block menu then acts on the whole set, in one undo step: delete, duplicate, move (Alt+Shift+Arrow), colour, and Turn into. Turn into only lists types that fit every selected block. Copy and paste keep the selected blocks.

Copy link to block in the block menu stores a blockId on that block and copies a URL ending in #block-<id>. Opening that URL scrolls to the block and highlights it. A duplicate of the block gets its own id. Blocks that were never linked omit the id from getJSON(). @tiptap/extension-unique-id is not a dependency; the id is assigned by the editor.

Versions, unknown blocks, and invalid content

Every document stores attrs.schemaVersion on the doc node. BLOCKCN_SCHEMA_VERSION is the version this build writes. Pass migrations to createEditorExtensions to bring an older document forward before it is checked. The key is the version you are migrating from, and the functions run in that order. A document with no version is treated as version 1.

A node this schema does not know is kept. It is shown as "Unsupported block" and editor.getJSON() writes the original node back, so a save does not drop it.

enableContentCheck is on. If the document is still invalid after migrations and wrapping, onContentError({ error, json, disableCollaboration }) runs. disableCollaboration() stops a collab session from syncing that document.

A React node view that throws while rendering is replaced by “This block failed to render”, with Retry and Copy JSON. onBlockError(error, node) runs, and getJSON() still contains that node. Typing in other blocks keeps working. Math catches a KaTeX failure inside its own view. Mentions are marks, so they have no node view to wrap.

import { createEditorExtensions } from "@/editor-core/schema/extensions";

const extensions = createEditorExtensions({
  migrations: {
    1: (json) => ({
      ...json,
      content: json.content?.map((node) =>
        node.type === "note" ? { ...node, type: "paragraph" } : node,
      ),
    }),
  },
  onContentError({ error, disableCollaboration }) {
    console.error(error);
    disableCollaboration();
  },
});

BLOCKCN_SCHEMA_VERSION is 1 in this release. A migration keyed 1 produces a document at version 2.

Next: tables, media and export.

On this page