Skip to the content

Frameworks

React

@dorvyn/react is the editor as React components and hooks, for React apps that run in the browser: Vite, Create React App, Remix, React Router, or your own setup. It works with React 18.3 and 19. Using Next.js? Its page is Next.js: the code there is different.

This page builds a complete document editor in a Vite app with an Express server: licensing for your signed-in users, saving to your database, opening where the person left off, and downloading as Word.

Install#

Terminal
npm install @dorvyn/react                 # the page
npm install @dorvyn/server express        # your server

1. Your server: the license route#

The page has no key. Your server licenses the editor for the user signed in to your app (strict mode), with your secret key in its environment:

Terminal
# The server's environment only; never a VITE_ variable
DORVYN_SECRET_KEY=dvn_sk_test_…
JavaScript
// server/index.js
import express from "express";
import { dorvynRoutes, nodeHandler } from "@dorvyn/server";
import { db, session } from "./app.js"; // your database and your sign-in

const app = express();
app.use(session);

// The editor's license, and saving as Word, for the signed-in user (strict mode).
app.post("/api/dorvyn/:action", express.json({ limit: "100mb" }), (req, res) =>
  nodeHandler(dorvynRoutes({ user: () => req.session?.userId }))(req, res),
);

app.listen(3001);
  • user returns your signed-in user's id, or nothing (then there's no license). It reads req in a closure, because dorvynRoutes itself is given a web Request, not Express's req.
  • The body limit is for saving as Word: the whole document, pictures included, goes through this route.

In development, let Vite pass /api to your server, so the page and its API share one origin (and your session cookie):

JavaScript
// vite.config.js
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],
  server: { proxy: { "/api": "http://localhost:3001" } },
});

In production, serve the built app and the API from the same origin: Express can serve dist/ (app.use(express.static("dist"))), or put both behind one reverse proxy. If your API must live on another origin, see Strict mode.

2. The editor on a page#

TSX
// src/Editor.tsx
import { DorvynEditor } from "@dorvyn/react";

export function Editor() {
  return <DorvynEditor serverUrl="/api/dorvyn" style={{ height: "100dvh" }} />;
}

That's the full editor, licensed for your signed-in user. Give it a height: it fills its box.

3. Saving to your database, and opening where they left off#

The editor gives you the document as JSON (EditorDocument). Store it, and open it again next time.

Add two routes to your server:

JavaScript
// server/index.js (continued)

// Your documents, as the editor gives them to you (JSON).
app.get("/api/documents/:id", async (req, res) => {
  if (!req.session?.userId) return res.sendStatus(401);
  const doc = await db.getDocument(req.params.id, req.session.userId);
  if (!doc) return res.sendStatus(404);
  res.json(doc);
});

app.put("/api/documents/:id", express.json({ limit: "100mb" }), async (req, res) => {
  if (!req.session?.userId) return res.sendStatus(401);
  if (req.body?.format !== "dorvyn.document") return res.status(400).json({ message: "Not a Dorvyn document." });
  await db.saveDocument(req.params.id, req.session.userId, req.body);
  res.sendStatus(204);
});

Store the document as it comes (a JSON or JSONB column, or an object in S3). Pictures are inside it, so it can be several megabytes.

The editor component, with autosave, a save status, Save, and a download as Word:

TSX
// src/DocumentEditor.tsx
import { useEffect, useRef, useState } from "react";
import { DorvynEditor, type Editor, type EditorDocument } from "@dorvyn/react";

type Status = "opening" | "saved" | "unsaved" | "saving" | "failed";

export function DocumentEditor({ id }: { id: string }) {
  const [status, setStatus] = useState<Status>("opening");
  const editor = useRef<Editor | null>(null);
  const opened = useRef(false);
  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);

  // Saves to your server. Throwing tells the person (Save and Ctrl+S show "Saving failed").
  async function save(doc: EditorDocument) {
    clearTimeout(timer.current);
    setStatus("saving");
    const res = await fetch(`/api/documents/${id}`, {
      method: "PUT",
      headers: { "content-type": "application/json" },
      body: JSON.stringify(doc),
    });
    if (!res.ok) {
      setStatus("failed");
      throw new Error("Your changes weren't saved. Try again.");
    }
    setStatus("saved");
  }

  // Opens the document as it was last saved (a new one starts blank).
  async function open(e: Editor) {
    editor.current = e;
    const res = await fetch(`/api/documents/${id}`);
    if (res.ok) await e.setDocument(await res.json());
    else if (res.status !== 404) throw new Error("The document couldn't be opened.");
    opened.current = true;
    setStatus("saved");
  }

  // Autosave: three seconds after the last change.
  function changed(doc: EditorDocument) {
    if (!opened.current) return; // the document being opened, not an edit
    setStatus("unsaved");
    clearTimeout(timer.current);
    timer.current = setTimeout(() => void save(doc).catch(() => {}), 3000);
  }

  // Warn before leaving with changes not saved yet.
  useEffect(() => {
    const warn = (event: BeforeUnloadEvent) => {
      if (status === "unsaved" || status === "saving" || status === "failed") event.preventDefault();
    };
    window.addEventListener("beforeunload", warn);
    return () => window.removeEventListener("beforeunload", warn);
  }, [status]);

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100dvh" }}>
      <header style={{ display: "flex", gap: 12, alignItems: "center", padding: 8 }}>
        <span>{LABELS[status]}</span>
        <button onClick={() => editor.current && void save(editor.current.getDocument()).catch(() => {})} disabled={status === "opening"}>
          Save
        </button>
        <button onClick={() => void editor.current?.commands.run("file.saveDocx")} disabled={status === "opening"}>
          Download as Word
        </button>
      </header>
      <DorvynEditor
        serverUrl="/api/dorvyn"
        onReady={(e) => void open(e).catch(() => setStatus("failed"))}
        onChange={changed}
        onSave={save}
        style={{ flex: 1, minHeight: 0 }}
      />
    </div>
  );
}

const LABELS: Record<Status, string> = {
  opening: "Opening…",
  saved: "All changes saved",
  unsaved: "Unsaved changes",
  saving: "Saving…",
  failed: "Not saved",
};

Use it with the document's id, for example from your router: <DocumentEditor id={params.id} />.

What it does:

  • Opening: onReady fetches the saved JSON and opens it with setDocument. The person sees the document exactly as they left it: text, formatting, tables, pictures, headers and footers, page setup and comments. It opens at the top of the first page: the cursor position and undo history aren't part of the document.
  • Autosave: onChange fires as they type (at most every 0.7 s), and the component saves three seconds after the last change. Opening a document doesn't fire onChange, so opening never saves.
  • Save and Ctrl+S: onSave makes the editor's own Save button and Ctrl+S call your save instead of downloading a file. Your header's Save button does the same with getDocument().
  • Download as Word: file.saveDocx makes the .docx from what's on screen (the saved document plus any changes since) through Dorvyn's export service, via your /api/dorvyn/export route, and downloads it named after the document.

Keeping the .docx on your server instead#

To store or email the Word file rather than download it, get it as a Blob:

TSX
async function attachWordFile() {
  const docx = await editor.current!.exportDocument("docx");
  const form = new FormData();
  form.append("file", docx, `${editor.current!.state.get().fileName}.docx`);
  await fetch(`/api/documents/${id}/attachments`, { method: "POST", body: form });
}

Drafts as well?#

Don't combine autosaveKey with this: your database is the copy that counts, and setDocument replaces any draft anyway. Drafts (autosaveKey="doc-42") are for apps that don't save documents themselves.

4. Your own toolbar#

Put pieces and your own controls inside <DorvynEditor>. The hooks work in any component inside it.

TSX
// src/WritingApp.tsx
import { CommandButton, Dialogs, Document, DorvynEditor, Panes, Ribbon, useCommand, useEditor, useEditorState } from "@dorvyn/react";

export function WritingApp() {
  return (
    <DorvynEditor serverUrl="/api/dorvyn">
      <Toolbar />
      <Ribbon tabs={["insert", "review"]} />
      <div style={{ display: "flex", height: "calc(100dvh - 120px)" }}>
        <Document style={{ flex: 1, minHeight: 0 }} />
        <Panes style={{ width: 280 }} />
      </div>
      <Dialogs />
    </DorvynEditor>
  );
}

function Toolbar() {
  const bold = useCommand("bold");                                  // { run, active, enabled, buttonProps }
  const italic = useCommand("italic");
  const editor = useEditor();                                       // null until it's ready
  const font = useEditorState((s) => s.format?.font ?? "", "");     // re-renders only when the font changes
  const words = useEditorState((s) => s.words, 0);

  return (
    <div role="toolbar" aria-label="Formatting">
      <button {...bold.buttonProps} aria-label="Bold"><b>B</b></button>
      <button {...italic.buttonProps} aria-label="Italic"><i>I</i></button>
      <select value={font} onChange={(e) => editor?.commands.run("fontFamily", e.target.value)} aria-label="Font">
        {editor?.lists.fonts.map((f) => <option key={f}>{f}</option>)}
      </select>
      <CommandButton command="table.insert">Table</CommandButton>
      <span>{words} words</span>
    </div>
  );
}

buttonProps gives a <button> its onClick, disabled, aria-pressed, and an onMouseDown that keeps the cursor in the document. Every command is in Commands, state and lists, and a full ribbon of your own is in Building your own ribbon.

5. Showing the license state#

The full editor shows it in its status bar. With your own layout, show it yourself:

TSX
import { useEditorState } from "@dorvyn/react";

const MESSAGES: Record<string, string> = {
  unavailable: "You're signed out. Sign in again to keep editing.",
  lapsed: "Reconnecting…",
  refused: "The editor isn't licensed for this site.",
  grace: "Working offline. Downloading as Word will be back soon.",
};

export function LicenseBanner() {
  const license = useEditorState((s) => s.license, "none");
  return MESSAGES[license] ? <p role="status">{MESSAGES[license]}</p> : null;
}

Put it inside <DorvynEditor>. All states are in Events and license states.

Props#

PropTypeWhat it does
serverUrlstringYour server's Dorvyn routes (strict mode)
licensestringA publishable key, instead of serverUrl. "" waits for one
autosaveKeystringKeep drafts in the browser under this name
logo, logoDarkstringYour logo on the full editor's File button and screen
theme"light" or "dark"The theme until the person picks one
animationsbooleanfalse: no animations until the person turns them on
exportUrl, engineUrlstringOnly for self-hosted export or serving the engine yourself
optionsPartial<EditorOptions>drafts, edition, fetch, getGrant (Options)
onReady(editor) => voidThe editor has started
onChange(document) => voidThe person changed the document (at most every 0.7 s)
onSave(document) => void | Promise<void>Save and Ctrl+S give you the document. Throw to say saving failed
onOpen(request) => voidThe editor wants a dialog, pane or view
onNotice(message) => voidA message for the person
onError(error) => voidThe editor couldn't start, or a command failed
className, style, idOn the element

Settings (serverUrl, license, options, autosaveKey) are read when the editor starts. To start it again with others, change the component's React key. Event handlers can change at any time.

Types come from the same package: import type { Editor, EditorDocument, EditorState, OpenRequest } from "@dorvyn/react".

Components and hooks#

ComponentPropsWhat it is
<Document>The pages
<Ribbon>tabs, themeThe ribbon, with some or all of its tabs
<RibbonTab>name, themeOne tab's groups, without the tab strip
<RibbonGroup>name, themeOne group, for example "font"
<CommandButton>command, childrenOne command as a button
<Dialogs>themeThe editor's dialogs and notices
<Panes>theme, navButtonThe navigation, find and comments panes
<ContextMenu>themeThe right-click menu

Each takes className, style and id. Tab and group names are in The full editor and layouts.

HookReturns
useEditor()The editor, or null until it's ready
useEditorState(pick, fallback)One part of the state, re-rendering only when it changes
useCommand(id, value?){ run, active, enabled, buttonProps }

Remix and React Router#

The component renders on the server as an empty element at its size, and starts in the browser once it has its settings, so server rendering needs nothing extra. Put the license route in a resource route:

TypeScript
// app/routes/api.dorvyn.$action.ts (Remix, React Router 7)
import { dorvynRoutes } from "@dorvyn/server";
import { getUserId } from "~/session.server"; // your session helper

const dorvyn = dorvynRoutes({ user: (request) => getUserId(request) });
export const action = ({ request }: { request: Request }) => dorvyn(request);

With a publishable key#

For development, demos or public pages without a server:

TSX
<DorvynEditor license={import.meta.env.VITE_DORVYN_KEY} style={{ height: "100dvh" }} />

A VITE_ value is built into your JavaScript, as any key the browser uses is. Use strict mode for signed-in products (How licensing works).