@docx-editor.dev/editor-api
Edit DOCX files through a supported subset of the Office.js object model. The API includes paragraphs, ranges, comments, and revisions. Use load() to queue reads and sync() to apply each batch atomically.
Run the API on a server over DOCX bytes or in the browser against an open editor. See Office.js compatibility for supported members and differences from Office.js.
npm install @docx-editor.dev/editor-api @docx-editor.dev/core
Server use requires Node.js ^20.16.0 || >=22.3.0.
Guides by task
Start with Runtime and setup and Batching, loading, and errors.
| Task | Guide |
|---|---|
| Read, insert, replace, or remove text | Text and ranges |
Split a paragraph with insertText() and \n, also as a tracked change | Split a paragraph |
| Find matches or use bookmarks | Search and navigation |
| Set fonts, paragraph properties, styles, or links | Formatting and styles |
| Create and configure lists | Lists and numbering |
| Work with table values, rows, columns, and cells | Tables and cells |
| Insert and resize images | Inline pictures |
| Insert fields, write their cached results, or calculate PAGE and NUMPAGES | Fields and pagination |
| Insert an equation from OOXML | Insert an equation |
| Propose a split, a field, or an equation as a tracked change | Tracked changes |
| Propose a model's paragraph rewrite as the fewest tracked changes | Propose an AI rewrite, with prepareRewrite from @docx-editor.dev/editor-api/agent |
| Set page geometry and edit headers, footers, or notes | Page layout and stories |
| Fill template controls and edit their metadata | Content controls |
| Discuss content and manage threads | Comments |
| Create, inspect, accept, or reject tracked changes | Tracked changes |
| Find any public object, method, property, or support type | API member directory |
On a server
The root entry opens DOCX bytes, edits the document, and returns the saved bytes.
import { readFile, writeFile } from 'node:fs/promises';
import { DocxEditor } from '@docx-editor.dev/editor-api';
const runtime = await DocxEditor.createServer(await readFile('contract.docx'), {
author: 'Review bot',
});
try {
const filled = await runtime.run(async (context) => {
const matches = context.document.body.search('{{cap}}', { matchCase: true });
matches.load('items');
await context.sync(); // Read the matching ranges.
for (const match of matches.items) match.insertText('$500k', 'Replace');
await context.sync(); // Commit all writes in one atomic batch.
return matches.items.length;
});
console.log(`replaced ${filled}`);
await writeFile('contract.filled.docx', await runtime.save());
} finally {
runtime.dispose();
}
createServer parses the document before resolving and does not retain the input buffer. You can then reuse or transfer that buffer. Each save() returns an independent Uint8Array. Load the saved bytes into a live editor to display server edits.
Create tracked changes on a server
Start with the Office.js developer guide for a complete server example and batching conventions.
Set document.changeTrackingMode = 'TrackMineOnly', then use standard Office.js editing methods. Supply the agent's author when opening the server or collaborative runtime:
await runtime.run(async (context) => {
const matches = context.document.body.search('within 7 days');
matches.load('items');
await context.sync();
if (matches.items.length !== 1) throw new Error('Choose a unique target');
context.document.changeTrackingMode = 'TrackMineOnly';
const replacement = matches.items[0]!.insertText('within 30 days', 'Replace');
await context.sync();
replacement.load('text');
await context.sync();
});
Use range.insertText(text, 'Before' | 'After') for insertions, and range.delete() or range.clear() for deletions. insertText() returns the inserted range. Mode assignments and edits commit together at sync(); failed batches preserve the previous mode and document. Load document.changeTrackingMode before reading it. Off is the initial mode.
This is a supported Office.js subset. TrackMineOnly applies to this server host and persists across its run() calls. It does not change peers' tracking settings or save a document-wide tracking policy. TrackAll fails with NotSupported. Browser tracked writes require the Pro review module; the runtime setting does not change the editor UI mode. Tracked text edits support one paragraph, including table-cell text, and adjacent sibling paragraphs outside collaboration. Tracked Paragraph.delete() and Range.delete() over whole paragraphs record deleted text and deleted paragraph marks, also in collaboration. Font, paragraph-format, paragraph-style, and readingOrder changes record property revisions, and paragraph insertion records inserted text and paragraph marks. Tracked edits can go inside or beside another author's pending text insertion or deletion, and each author's change stays a separate decision. The runtime refuses edits that touch your own pending change, another author's paragraph mark, formatting, move, or structural change, and text inside a row with a pending insertion or deletion. Tracked paragraph splits through insertText() with \n, fields through insertField() with results through Field.result, and one equation at a time through insertOoxml() produce native revisions. Other structural changes refuse while tracking. For the complete list, see Revisions. Comments and revision decisions remain available. Set Off explicitly when permanent edits are intended.
See the server-agent review example for Hocuspocus, stale-read handling, and the review lifecycle.
In the browser
Pass an open core, React, or Vue editor to createBrowser(). Edits use the editor's undo history. Save through the owning editor.
import { DocxEditor } from '@docx-editor.dev/editor-api/browser';
const runtime = DocxEditor.createBrowser(editor, { author: 'Demo Reviewer' });
try {
await runtime.run(async (context) => {
const heading = context.document.body.paragraphs.getFirstOrNullObject();
heading.load('text');
await context.sync();
if (!heading.isNullObject) heading.font.bold = true;
await context.sync();
});
} finally {
runtime.dispose();
}
Use the /browser entry for an open editor. Use the root entry on servers to exclude browser rendering code from the bundle.
Supply author for comments, replies, and tracked edits. Browser review writes also require the Pro review module and an editable document. Handle errors by code. See Comments and Tracked changes for supported operations.
Programming model
- Load properties before reading them. Load collection
itemsbefore item properties. - Batch independent writes with
sync(). A failed batch applies no writes; earlier successful syncs remain committed. - Sync after insertion before using the returned object.
- Keep proxies inside
runtime.run(), or explicitly track and adopt them across runs. - Search again after editing a paragraph. Existing ranges retain their original offsets.
- Check
isNullObjectafter sync when using a null-object accessor. - Check nullable font values and review dates before using them.
See Batching, loading, and errors for transaction limits, proxy lifetimes, and error recovery.
Office.js compatibility
The API implements a documented subset of the Office.js object model. It runs without an Office.js host and does not require an Office.js package. See Office.js compatibility for supported operations, runtime differences, and compatibility reports.
Server page-field updates require a measurer configured with font resources. See Fields and pagination for setup and a runnable report agent.
To upgrade from the former reviewer, bridge, MCP, or chat APIs, see Migration.
Packages
| Package | Description |
|---|---|
@docx-editor.dev/react | React adapter. <DocxEditor>, provider primitives, hooks, and compound chrome. |
@docx-editor.dev/core | Framework-agnostic engine: OOXML read/write, canonical document tree, layout, paint. |
@docx-editor.dev/i18n | Shared locale strings and types. |
@docx-editor.dev/pro | Tracked changes, comments, and custom nodes. |
@docx-editor.dev/editor-api | Supported Office.js subset for document editing on a server or in an open editor. |
Which API for which job
Use the React or Vue adapter hooks, the review hooks, and DocxEditorReview from @docx-editor.dev/pro/react or @docx-editor.dev/pro/vue to build browser review controls. Use the editing API in @docx-editor.dev/editor-api for document automation. It follows the Office.js object model and runs in browser and server hosts.
| Task | Browser controls (React or Vue) | Document automation |
|---|---|---|
| Comment on found text | editor.findMatches, editor.selectMatch, then useReview().comment | body.search, then Range.insertComment |
| Reply to a thread | useReview().reply(item, text) | Comment.reply(text) |
| Record a tracked replacement | Suggesting mode, then editor.exec({ type: 'replaceMatch', match, text }) | document.changeTrackingMode = 'TrackMineOnly', then Range.insertText(text, 'Replace') |
| Propose an AI rewrite as tracked changes | prepareRewrite through DocxEditor.createBrowser | prepareRewrite from @docx-editor.dev/editor-api/agent |
| Accept or reject a change | useReview().accept(item) or useReview().reject(item) | Revision.accept() or Revision.reject() |
| Open a change without scrolling | useReview().setActive(key, { reveal: false }) | Not applicable: no viewport |
| Highlight ranges | useHighlights(name, source, options) | Not applicable |
| Custom review rail cards | DocxEditorReview with preset set to false, useReviewCardHeights, useStackedReviewPositions, and useReviewRailMetrics | Not applicable |
| Comment-on-selection button | DocxEditorReview.AddComment as a direct child of DocxEditorReview, or useEditorCommand('review.addComment') | Not applicable |
| Page setup and paragraph dialogs | DocxEditor.PageSetupDialog or DocxEditor.ParagraphDialog | Section.pageSetup, and Paragraph properties such as alignment |
This package ships the task recipes in docs/index.md. They are also on the site: Task recipes.
License
This package uses the EigenPal Pro License. See pricing for license and support options.
Contributing
Contributions welcome. See CONTRIBUTING.md for setup, tests, and the one-time CLA signature.
Commercial support
[!TIP] Questions or custom features? Email [email protected].