Frameworks
Next.js
@dorvyn/next is the editor for Next.js 15 and later: the React components and hooks, already marked as client components, plus @dorvyn/next/server for your route handlers and @dorvyn/next/csp for your content security policy. Using React without Next.js? Its page is React.
This page builds a complete document editor with the App Router: licensing for your signed-in users, the saved document read on the server so the page opens with it, autosave through a route handler, and downloading as Word. The Pages Router is at the end.
Install#
npm install @dorvyn/next@dorvyn/next/server is @dorvyn/server, so there's nothing else to install.
1. The license route#
# .env.local (the server only: never prefix it with NEXT_PUBLIC_)
DORVYN_SECRET_KEY=dvn_sk_test_…// app/api/dorvyn/[action]/route.ts
import { dorvynRoutes } from "@dorvyn/next/server";
import { auth } from "@/auth";
export const POST = dorvynRoutes({
user: async () => (await auth())?.user?.id,
});user returns your signed-in user's id, or nothing (then there's no license, and the route answers 401). Use an opaque id, never an email. With other auth libraries:
// Clerk
import { auth } from "@clerk/nextjs/server";
export const POST = dorvynRoutes({ user: async () => (await auth()).userId });
// Supabase
import { createClient } from "@/utils/supabase/server";
export const POST = dorvynRoutes({ user: async () => (await (await createClient()).auth.getUser()).data.user?.id });2. The editor on a page#
// app/editor/page.tsx (a Server Component)
import { DorvynEditor } from "@dorvyn/next";
export default function EditorPage() {
return <DorvynEditor serverUrl="/api/dorvyn" style={{ height: "100dvh" }} />;
}That's the full editor, licensed for your signed-in user, used straight from a Server Component. Give it a height.
3. Saving to your database, and opening where they left off#
The editor gives you the document as JSON (EditorDocument). Store it in your database, read it on the server when the page opens, and the person continues where they left off.
Saving: a route handler.
// app/api/documents/[id]/route.ts
import type { EditorDocument } from "@dorvyn/next";
import { auth } from "@/auth";
import { db } from "@/lib/db";
export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
const userId = (await auth())?.user?.id;
if (!userId) return new Response(null, { status: 401 });
const doc = (await request.json()) as EditorDocument;
if (doc?.format !== "dorvyn.document") return Response.json({ message: "Not a Dorvyn document." }, { status: 400 });
await db.saveDocument((await params).id, userId, doc);
return new Response(null, { status: 204 });
}Opening: the page reads the saved document on the server and gives it to the editor.
// app/documents/[id]/page.tsx (a Server Component)
import { redirect } from "next/navigation";
import { auth } from "@/auth";
import { db } from "@/lib/db";
import { DocumentEditor } from "./document-editor";
export default async function DocumentPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const userId = (await auth())?.user?.id;
if (!userId) redirect("/sign-in");
// The document as it was last saved, read on the server: the page opens with it.
const saved = await db.getDocument(id, userId);
return <DocumentEditor id={id} saved={saved} />;
}The editor: a client component, with autosave, a save status, Save, and a download as Word.
// app/documents/[id]/document-editor.tsx
"use client";
import { useEffect, useRef, useState } from "react";
import { DorvynEditor, type Editor, type EditorDocument } from "@dorvyn/next";
type Status = "opening" | "saved" | "unsaved" | "saving" | "failed";
export function DocumentEditor({ id, saved }: { id: string; saved: EditorDocument | null }) {
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 through your route handler. 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 what the server read (a new document starts blank).
async function open(e: Editor) {
editor.current = e;
if (saved) await e.setDocument(saved);
opened.current = true;
setStatus("saved");
}
// Autosave: three seconds after the last change.
function changed(doc: EditorDocument) {
if (!opened.current) return;
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",
};What it does:
- Opening: the Server Component reads the saved JSON, and
onReadyopens it withsetDocument. 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:
onChangefires as they type (at most every 0.7 s), and the component saves three seconds after the last change. Opening a document doesn't fireonChange, so opening never saves. - Save and Ctrl+S:
onSavemakes the editor's own Save button and Ctrl+S call yoursaveinstead of downloading a file. - Download as Word:
file.saveDocxmakes the.docxfrom what's on screen (the saved document plus any changes since) through Dorvyn's export service, via your/api/dorvyn/exportroute.
Event props such as onSave and onChange are functions, so they're set in a client component ("use client"), never passed from a Server Component.
Large documents: the saved document travels to the page inside the Server Component's payload. That's right for most documents. If yours often carry many large pictures (tens of megabytes), fetch the document from a GET route handler in onReady instead, as on the React page.
Why a route handler, not a server action#
A server action works too, but Next.js limits a server action's request to 1 MB by default, and a document with a few pictures is larger. If you prefer a server action, raise the limit:
// next.config.ts
export default {
experimental: { serverActions: { bodySizeLimit: "50mb" } },
};Request size limits#
The whole document goes through two of your routes: PUT /api/documents/[id] when saving, and /api/dorvyn/export when downloading as Word. Next.js doesn't limit a route handler's body, but:
- With a
proxy.tswhose matcher includes these routes, Next.js buffers request bodies only up to 10 MB (proxyClientMaxBodySize). Leave/apiout of the matcher (the content security policy example does), or raise it. - Your host may cap request bodies. On Vercel, functions accept request bodies up to 4.5 MB. For larger documents, run these routes where larger bodies are allowed (your own Node server, a container), or upload large documents to storage first.
4. Your own toolbar#
Components that use the hooks are client components:
// app/editor/toolbar.tsx
"use client";
import { useCommand, useEditor, useEditorState } from "@dorvyn/next";
export function Toolbar() {
const bold = useCommand("bold");
const editor = useEditor();
const font = useEditorState((s) => s.format?.font ?? "", "");
const words = useEditorState((s) => s.words, 0);
return (
<div role="toolbar" aria-label="Formatting">
<button {...bold.buttonProps} aria-label="Bold"><b>B</b></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>
<span>{words} words</span>
</div>
);
}// app/editor/page.tsx (a Server Component)
import { Dialogs, Document, DorvynEditor, Panes, Ribbon } from "@dorvyn/next";
import { Toolbar } from "./toolbar";
export default function EditorPage() {
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>
);
}The components, hooks and props are the same as React's: see React.
5. Content security policy#
The editor works under a strict policy. With pages rendered per request, a nonce from proxy.ts, and withDorvynCsp adding the editor's sources: see Content security policy for the complete proxy.ts.
Server rendering#
On the server, the editor renders as an empty element at the size you give it, so nothing moves when it starts. It starts in the browser once React has given it its settings (onSave, options and the rest), so everything you pass applies from the start. There's nothing to configure, and no need for next/dynamic.
Pages Router#
The same package works in pages/. The license route is an API route, with Next's body parser allowed large documents:
// pages/api/dorvyn/[action].ts
import type { NextApiRequest, NextApiResponse } from "next";
import { dorvynRoutes, nodeHandler } from "@dorvyn/next/server";
import { auth } from "@/auth";
// Saving as Word sends the whole document: allow large bodies.
export const config = { api: { bodyParser: { sizeLimit: "100mb" } } };
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const userId = (await auth())?.user?.id; // your session, read from req (Auth.js: getServerSession(req, res, authOptions))
await nodeHandler(dorvynRoutes({ user: () => userId }))(req, res);
}// pages/editor.tsx
import { DorvynEditor } from "@dorvyn/next";
export default function EditorPage() {
return <DorvynEditor serverUrl="/api/dorvyn" style={{ height: "100vh" }} />;
}For saving, use an API route for your documents the same way (pages/api/documents/[id].ts, with the same sizeLimit), and the editor component from step 3, loading the document in getServerSideProps instead of the Server Component.
Static export#
With output: "export", Next doesn't run a server, so there are no route handlers. Put the license route on another server you have (see Strict mode) and point serverUrl at it, or use a publishable key.
With a publishable key#
For development, demos or public pages:
<DorvynEditor license={process.env.NEXT_PUBLIC_DORVYN_KEY!} style={{ height: "100dvh" }} />A NEXT_PUBLIC_ value is built into the page's JavaScript, as any key the browser uses is. See How licensing works.