mroffice-embed
v1.6.0
Published
Embed MR Office's Word, Excel, PowerPoint, PDF, Code and Handwriting editors in your web app: `npx mroffice-embed init` sets it up (app, keys, server route, page); a tiny dependency-free client for the MR Office embed API with React, Vue, Angular, Svelte
Maintainers
Readme
mroffice-embed
Put MR Office's Word, Excel, PowerPoint, PDF, Code and Handwriting editors in
your own web app.
A tiny, dependency-free client for the MR Office embed API: it frames the
editor, hands it a session token your server signed, and tells you when the
document is ready, changed and saved. Its server half
(mroffice-embed/server) signs those tokens and verifies the save callbacks.
Full guide: https://mroffice.ai/developers/embed (as one Markdown file, for AI agents: https://mroffice.ai/developers/embed.md)
One command
In your project's folder:
npx mroffice-embed init # add --yes when no one can answer promptsIt detects the framework (Next.js App or Pages Router, Vite + React/Vue,
Express or any Node server, Nuxt, SvelteKit, FastAPI, Flask, Django, or a
plain HTML site), opens your browser once to sign in to MR Office and
Allow, creates an embed app in your account, writes MROFFICE_APP_ID,
MROFFICE_SECRET_KEY and MROFFICE_WEBHOOK_SECRET to .env.local or .env
(never printed; .env* is added to .gitignore), adds a server route
(GET /api/mroffice/session) that mints session tokens and an editor page
(/mroffice-editor), installs this package and prints what is left to do.
Running it again changes nothing that is already there.
| Option | |
| --- | --- |
| --yes | never ask (scripts and AI coding agents) |
| --framework <id> | next-app, next-pages, nuxt, sveltekit, vite-express, vite, vue, express, fastapi, flask, django, generic |
| --origin <https://…> | a production origin that may show the editor (repeatable; http://localhost:* and http://127.0.0.1:* are always allowed) |
| --name, --dir, --env-file | the app's name, the project folder, where the keys go |
| --no-browser, --no-install, --force, --dry-run, --json | |
Already have an app? Put MROFFICE_APP_ID and MROFFICE_SECRET_KEY in the
env file or the environment (in CI also MRO_EMBED_APP_ID /
MRO_EMBED_SECRET_KEY) and init uses it without signing in.
By hand
npm install mroffice-embedYour server (one route):
import { createSessionToken } from "mroffice-embed/server";
app.get("/editor-token", requireLogin, async (req, res) => {
res.json({
token: await createSessionToken({
appId: process.env.MROFFICE_APP_ID,
secretKey: process.env.MROFFICE_SECRET_KEY, // mro_sk_… (server only)
file: { key: "contract-42", name: "contract.docx", url: signedUrl },
user: { id: req.user.id, name: req.user.name },
mode: "edit",
}),
});
});Your page:
import { open } from "mroffice-embed";
const editor = open({
container: "#editor",
appId: "YOUR_APP_ID", // the editor starts loading while the token is signed
// asked again whenever a fresh token is needed: before the session ends,
// after a reload, and by setMode() and setLocale()
token: ({ mode }) => fetch(`/editor-token?mode=${mode ?? "edit"}`).then((r) => r.json()).then((b) => b.token),
locale: "en",
theme: "light",
ui: { toolbar: "full" },
onReady: (event) => console.log(event.document),
onChange: (event) => console.log("modified", event.modified),
onSave: (saved) => console.log("version", saved.version, saved.downloadUrl),
onError: (error) => console.error(error.code, error.hint ?? error.message),
onConnectionChange: ({ online }) => console.log(online ? "back online" : "offline; edits are kept"),
});
await editor.ready;
const saved = await editor.requestSave();
await editor.setLocale("ja"); // reloads in Japanese, same document
editor.focus();
await editor.destroy();Without a bundler, load https://mroffice.ai/embed/v1/embed.js and call
MROffice.open({...}) — the same code.
Session tokens
A JWT signed HS256 with your app's secret key (mro_sk_…, from the
developer console), for one person and one file:
{
"iss": "<app id>", "aud": "mroffice-embed",
"iat": 1795100000, "exp": 1795100600, "jti": "<unique>",
"file": { "key": "contract-42", "name": "contract.docx", "url": "https://…signed…" },
"mode": "edit",
"user": { "id": "user-7", "name": "Alex" }
}file.name may be any format the editors open: .docx .xlsx .pptx .pdf, and
.doc .dot .dotx .rtf .odt .txt .md .html .xls .xltx .ods .csv .tsv .ppt .potx
.odp — each saved back in its own format. Source files (.py .js .ts .json .sql
.go .java .c .cpp .cs .rs .rb .php .swift .kt .yaml .toml .xml .css .sh …)
open in the Code editor and are saved back byte for byte in their own
encoding and line endings; .mrink opens in the Handwriting editor (pens,
highlighters, erasers, lasso, ruler on handwriting paper) and is saved back as
.mrink.
file.new: true (with a name, no url) opens a blank document of that
format — notes.mrink, scratch.py, draft.docx — the first time the key is
used; its first save sends it to you:
file: { key: `notes-${user.id}`, name: "Lecture notes.mrink", new: true }Mint it on your server only (createSessionToken from
mroffice-embed/server does it in Node 18+, Deno, Bun and edge functions).
The editor fetches the file, everyone with a token for the same file.key
edits it together, and each save is POSTed to your callback URL,
HMAC-signed with your webhook key:
import { verifyCallback } from "mroffice-embed/server";
// the raw body, exactly as received
const event = await verifyCallback(rawBody, request.headers["mro-signature"], process.env.MROFFICE_WEBHOOK_SECRET);A token starts one session, once. Pass token as a function and the SDK
asks it for a fresh one whenever it needs to, with
{ reason: "start" | "refresh" | "reload" | "mode", mode }.
Building on localhost
Turn on Allow localhost for the app in the developer console: pages on
http://localhost and http://127.0.0.1, at any port, can then show the
editor (the app's origins gain http://localhost:* and
http://127.0.0.1:*). With a file.local token you need no file server
either. The console's Events view lists each app's last 50 events: the
starts MR Office refused (and why), failed opens, saves and callbacks.
Errors
Every onError (and every rejected promise) is
{ code, message, fatal, hint?, docs? }: hint says what to do,
docs links to the code in the
error reference. The table is
exported as EMBED_ERROR_HINTS.
Robustness
- The frame reloaded (by your page,
setLocaleor a crash) is started again with a fresh token from your token function;onReadyfires again. onConnectionChange({ online })tells you when the editor lost or regained its link to MR Office; edits typed meanwhile are kept.- Several editors on one page are independent;
destroy()ends the session, removes the iframe and its listener, and rejects what was pending. MROffice.preconnect()opens the connection to the editor early;open()calls it, and afile: { name }(or a token string) lets the frame start loading that file kind's editor before the token arrives.editor.capabilitieslists what the frame can do (from itshello).
Files from the person's computer
With no file store of your own, a token can let the person open a file from
their computer: "file": { "key": "<a fresh key>", "local": true } (optional
accept, max_bytes, replace), and the app's "Allow people to open files
from their computer" switch on in the developer console. The editor shows a
drop zone; your page can also hand it a file:
const editor = open({
container: "#editor",
token,
onAwaitingFile: ({ accept, maxBytes }) => console.log("waiting for", accept, maxBytes),
onFileOpened: ({ name, size }) => console.log("opened", name, size),
});
input.addEventListener("change", () => editor.openFile(input.files[0]));A second file is refused unless the token has replace: true. Saves work as
for any file; the callback's document.source is "local".
Features, downloads and permissions
The embedded editor is MR Office's own editor: pictures (Insert › Picture,
paste, drag and drop), every export format, printing, find and replace,
comments and tracked changes (shown with your token's user.name), version
history and restore, charts, SmartArt, equations, formulas, and PDF
annotation, editing, signing and forms. AI is not part of it.
MROffice.open({
container: "#editor",
token,
// Each is on unless set to false.
ui: { features: { export: true, print: true, versionHistory: true, comments: true } },
// "browser" (default): the browser saves exports and pictures, and
// onDownload tells you. "host": the browser saves nothing and each file
// comes to onDownload as event.blob (or event.url, a short-lived link).
downloads: "browser",
onDownload: (event) => console.log(event.name, event.handledBy),
});ui.features.export: falseremoves Export and Download; the editor saves no file (handledBy: "refused").print: falseremoves Print and ignores ⌘P / Ctrl+P.versionHistory: falseandcomments: falseremove those panes' buttons.- The iframe is created with
allow="clipboard-read; clipboard-write; fullscreen; display-capture; local-fonts; microphone; camera; autoplay"(DEFAULT_ALLOW): copy and paste, slide shows and PDF presentation, screen capture, installed fonts, recording, and a slide's media. Passallowto grant fewer. A frame host of your own that usessandboxmust keepallow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals allow-downloads(Word prints from a new window).
Modes, permissions and watermark
The token decides what the person may do, on the server: mode is edit,
view, comment (read only, comments allowed), review (every edit a
tracked change) or fillForms (form fields only) — the last three are the
Word editor's lanes; a workbook, deck, PDF, code file or handwriting document
opens them read only. Narrow it
with permissions and mark the editor with a watermark:
const token = await createSessionToken({
appId, secretKey, file,
user: { id: user.id, name: user.name, email: user.email },
mode: "review",
permissions: { download: false, print: true, copy: false, export: ["pdf"], acceptRejectChanges: false },
watermark: { text: "{user.email} {datetime}", inExports: true }, // on screen and in every PDF
});Code and handwriting
// A code file: read and write it as the editor holds it ("\n" line endings;
// the file's own come back when it is saved).
const { text, language } = await editor.code.getText();
await editor.code.insertText("# Reviewed\n", { location: "start" });
await editor.code.setSelection({ line: 3 }, { line: 5, column: 1 });
// A handwriting document: its strokes, or erase them all (one Undo step).
const { count } = await editor.ink.getStrokes();
await editor.ink.clear();
const pdf = await editor.document.export("pdf"); // or "mrink", "docx"Running code is off in an embedded Code editor. A token may turn it on with
features: { run: true } for an app on Pro or above; each run then counts as
one server job (billed as a session). Code and handwriting files are not
offered to WOPI hosts.
People, mentions and events
MROffice.open({
container: "#editor",
token,
onRequestUsers: (query) => searchMyUsers(query), // [{ id, name, email?, avatarUrl? }], for "@" in comments
onUsersChange: ({ users }) => renderAvatars(users), // who is in the document
onMention: ({ mentioned, text }) => notify(mentioned, text),
});Subscribe the app to events (document.opened, user.joined,
comment.created, comment.mention, document.locked, … — EVENT_TYPES
from mroffice-embed/server) in the developer console; each is POSTed to
your webhook URL, signed like the save callback, and checked with
verifyWebhook(rawBody, header, webhookSecret).
Conversion, templates, compare and the Document Builder (server)
mroffice-embed/server also has a client for MR Office's server APIs, with
your app's secret key (never in a browser):
import { createClient } from "mroffice-embed/server";
const mro = createClient({ secretKey: process.env.MROFFICE_SECRET_KEY });
// Any Office, OpenDocument, iWork, e-book or Visio file, PDF, picture or .mrink to pdf, docx, xlsx, pptx, odt/ods/odp and their templates, epub, html, txt, md, csv/tsv (csv_input / csv_output: delimiter, encoding) or page images
const job = await mro.convert({ file: { url: signedUrl, name: "q3.docx" }, outputFormat: "pdf" });
const pdf = await mro.download(job);
// A .docx/.xlsx/.pptx template with {{tags}}, {{#loops}} and {{%pictures}}; a list of records is a mail merge
const letters = await mro.fillTemplate({ template: { uploadId }, data: customers, merge: { mode: "zip", file_name: "letter-{{id}}" } });
// Two .docx versions as one with tracked changes, and a summary of every change
const redline = await mro.compare({ original: { url: v1 }, revised: { url: v2 }, options: { author: "Legal" } });
console.log(redline.result.comparison.changes);Each call waits for its job (polling past the server's own wait) and throws an
MROfficeApiError with the API's code when it fails; async: true answers
the queued job, webhook: true has your callback URL told when it ends, and
idempotencyKey makes a retry safe. The full reference:
https://mroffice.ai/developers/embed/conversion, /embed/templates and
/embed/compare.
Document Builder
build() makes or changes Word, Excel, PowerPoint and PDF files from a
script (JavaScript against an object model named after ONLYOFFICE Document
Builder's) or from Builder JSON. The script runs in MR Office's sandbox (no
network, no files, bounded time and memory); MR Office's own writers make
the files.
const job = await mro.build({ script: await readFile("invoice.js", "utf8"), argument: { number: 1042, lines } });
const zip = await mro.download(job); // several SaveFile outputs: a ZIP, and job.files[n].download_url each
const filled = await mro.build({
document: { type: "pdf", open: "form.pdf", edits: [{ action: "fill_form", fields: { name: "Ada", agree: true } }] },
inputs: [{ url: signedFormUrl, name: "form.pdf" }],
});Script authors get types with /// <reference types="mroffice-embed/builder" />,
and npx mroffice-embed build invoice.js --argument data.json --out ./out
runs a script from the command line (the key from MROFFICE_SECRET_KEY).
Reference: https://mroffice.ai/developers/embed/builder.
Sessions and documents from your server
import { createClient } from "mroffice-embed/server";
const mro = createClient({ secretKey: process.env.MROFFICE_SECRET_KEY });
// One call: the file you hold is stored and the session token names it.
const { token } = await mro.createSession({
file: { key: "contract-42", name: "contract.docx", data: bytes }, // or { uploadId } / { url }
user: { id: user.id, name: user.name },
mode: "edit",
});
const doc = await mro.getDocument("contract-42"); // version, open sessions, last save
const saved = await mro.saveDocument("contract-42"); // save now (the callback follows)
const file = await mro.downloadDocument("contract-42"); // the newest saved file
for (let page = await mro.listDocuments(); ; ) { // cursor pages, newest first
handle(page.items);
if (!page.hasMore) break;
page = await mro.listDocuments({ startingAfter: page.items.at(-1).key });
}Missed a webhook? Every event is kept 30 days (also for apps without a webhook URL) and reads exactly as its webhook body:
const { items } = await mro.listEvents({ type: "document.saved", createdGte: lastRun });
const log = await mro.listDeliveries(items[0].id); // each attempt: status, latency, error, next retry
await mro.redeliver(items[0].id); // send it again now (idempotent)Every call has a timeout (timeoutMs, default 120 s) and retries what the
API marks retryable -- rate limits after Retry-After, 5xx, network errors --
up to maxRetries times (default 2). Each POST carries an Idempotency-Key
(pass your own as idempotencyKey, or the client makes one), so a retried
upload, session or save is done once. Refusals throw MROfficeApiError
with code, status, details, retryable, requestId and retryAfter.
The REST API itself is described by an OpenAPI 3.1 document:
https://mroffice.ai/api/v1/embed/openapi.json. Its conventions: errors are
{ error: { code, message, details, request_id, retryable } }; rate-checked
responses carry RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset;
lists are { items, has_more } with limit and starting_after; webhook
envelopes carry api_version (2026-11-22) and are signed
MRO-Signature: t=…,v1=… (verifyCallback checks it and its age).
Framework components
One package, a component per framework (subpath exports; each framework is an optional peer dependency, so a bundle takes only the entry it imports):
| Import | Framework | |
| --- | --- | --- |
| mroffice-embed/react | React 17+, Next.js App Router | <MROfficeEditor ref={editorRef} … /> (a client component; renders an empty container on the server) |
| mroffice-embed/vue | Vue 3.3+, Nuxt | <MROfficeEditor ref="editor" @save="…" />, useMROfficeEditor(container, options) |
| mroffice-embed/angular | Angular 17+ | standalone MROfficeEditorComponent (<mroffice-editor (save)="…">), partially compiled (Ivy) |
| mroffice-embed/svelte | Svelte 4/5, SvelteKit | <MROfficeEditor bind:editor onSave={…} />, the use:mroffice action |
| mroffice-embed/element | any | <mroffice-editor> Web Component (mroffice-save, … events); also https://mroffice.ai/embed/v1/element.js |
import { MROfficeEditor } from "mroffice-embed/react";
<MROfficeEditor tokenUrl="/api/mroffice/session" onSave={(saved) => console.log(saved.version)} style={{ height: "80vh" }} /><MROfficeEditor token-url="/api/mroffice/session" @save="(saved) => console.log(saved.version)" style="height: 80vh" />Props are open()'s options, plus tokenUrl: a route of your server that
answers { token, appId?, origin? } (or the token as text), called with
?reason=…&mode=… whenever a fresh token is needed (what init writes at
/api/mroffice/session). Callbacks and the token function never reopen the
editor; theme/ui.theme and locale/mode are changed in place; another
file, app, origin, ui or downloads opens a new editor. The handle (ref,
template ref, bind:editor, the Angular component, the element) has
requestSave(), setMode(), setTheme(), setLocale(), focus(),
openFile(), destroy(), ready and current, and stays the same across a
reopen. React's StrictMode and a moved element keep the session.
Mobile
Native wrappers host the same editor in a WebView with the same token flow
and a bridge for events and commands: apps/mroffice-embed-mobile/ (iOS
Swift package, Android library, React Native component, Flutter package).
They load one page, dist/webview/host.html (this SDK and
src/webview.ts, inline), at a base URL that is one of the app's allowed
origins; the app's token provider asks its own server for each token.
Theming and white-label (Pro and above)
open({
container: "#editor",
token,
ui: {
brandName: "Acme Docs",
theme: { colorScheme: "system", accent: "#0057d9", background: "#f5f7fb", dark: { accent: "#7aa7ff" },
fontFamily: "Segoe UI", radius: 6, density: "comfortable", logoUrl: "https://cdn.acme.example/logo.svg" },
},
});
editor.setTheme({ accent: "#b42318" });MR Office checks the theme on its server: on Free and Starter the editor
keeps its own look (onError embed_white_label_not_in_plan, not fatal);
colours keep WCAG AA contrast (an accent is moved to the nearest passing
shade of its hue, embed_theme_adjusted); fonts are those in
EMBED_THEME_FONTS; the logo (https, PNG/JPEG/GIF/WebP/SVG, 256 KB) is
fetched by MR Office's proxy. The developer console's Theme tab previews and
saves a theme for the app (a page's ui.theme overrides it key by key).
Example
examples/node-partner/server.mjs is a whole partner app in one
dependency-free Node file: its page, token minting, file serving, and a
verified callback receiver.
MROFFICE_APP_ID=… MROFFICE_SECRET_KEY=mro_sk_… MROFFICE_WEBHOOK_SECRET=mro_whsec_… \
node examples/node-partner/server.mjsBuilding
node scripts/build.mjs writes dist/ (ES modules and type declarations,
the framework entries, dist/webview/host.html) and the scripts MR Office
serves (apps/web/public/embed/v1/embed.js, element.js). The Angular
entry is partially compiled by node scripts/build-angular.mjs (its
compiler lives in scripts/angular: npm --prefix scripts/angular ci) into
src/angular/compiled/, which is committed. npm run test:frameworks runs
the components' tests.
node scripts/build.mjs --check fails when the served script is stale.
MIT licensed.
