# Quick start

Source: https://mroffice.ai/en/developers/embed/quick-start

### The fastest way: npx mroffice-embed init

In your project's folder, one command does the three steps below for you: it finds your framework (Next.js, Vite, Express, Nuxt, SvelteKit, FastAPI, Flask, Django or a plain HTML site), creates an app in your MR Office account after one Allow in the browser, writes its keys to .env.local or .env (never printed, and kept out of git), and adds a server route that signs session tokens plus a page that opens the editor. AI coding agents run it with --yes. Running it again changes nothing that is already there. Or do it by hand:

```bash
# in your project's folder: an app in your account (one "Allow" in the browser),
# its keys in .env.local / .env (never printed, kept out of git), a server route
# that signs session tokens and a page that opens the editor
npx mroffice-embed init

# AI coding agents and scripts: no questions (--origin adds a production origin)
npx mroffice-embed init --yes --origin https://app.example.com
```

### 1. Make an app

In the developer console, choose New app. Give it a name, the origins of the pages that will show the editor (for example https://app.example.com — exact origins, https only), and optionally your callback URL. Copy the two keys shown: the secret key (mro_sk_…) signs session tokens and calls the API; the webhook key (mro_whsec_…) verifies callbacks. They are shown once. Open a sample file to see the editor working before you write any code. While you build on your own computer, turn on Allow localhost: any http://localhost or http://127.0.0.1 page, at any port, can then show the editor.

### 2. Mint a session token on your server

Node, with the package's server helper (also Deno, Bun, edge functions):

```js
// server.js — your token endpoint, with the package's server helper
// (Node 18+, Deno, Bun, edge functions; npm install mroffice-embed).
import { createSessionToken } from "mroffice-embed/server";

app.get("/api/contracts/:id/editor-token", requireLogin, async (req, res) => {
  const contract = await contracts.get(req.params.id, req.user);   // your own access check
  const token = await createSessionToken({
    appId: process.env.MROFFICE_APP_ID,          // from the developer console
    secretKey: process.env.MROFFICE_SECRET_KEY,  // mro_sk_… (server only)
    file: {
      key: `contract-${contract.id}`,           // everyone with this key edits one document
      name: contract.fileName,                   // .docx .xlsx .pptx .pdf
      url: contract.signedDownloadUrl(),         // where MR Office reads it (https)
      version: contract.etag,                    // optional
    },
    user: { id: req.user.id, name: req.user.name },
    mode: contract.canEdit(req.user) ? "edit" : "view",
  });
  res.json({ token });
});
```

Or without the package: Node, no dependencies:

```js
// server.js — mint a session token for one person and one file (Node 18+).
import { createHmac, randomUUID } from "node:crypto";

const APP_ID = process.env.MROFFICE_APP_ID;          // from the developer console (mroffice.ai/developers/console)
const SECRET = process.env.MROFFICE_SECRET_KEY;      // mro_sk_… (server only)

const b64url = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");

export function mintSessionToken({ fileKey, fileName, fileUrl, version, userId, userName, mode = "edit" }) {
  const now = Math.floor(Date.now() / 1000);
  const header = { alg: "HS256", typ: "JWT" };
  const claims = {
    iss: APP_ID,
    aud: "mroffice-embed",
    iat: now,
    exp: now + 600,                 // at most 3600
    jti: randomUUID(),              // single use
    file: { key: fileKey, name: fileName, url: fileUrl, version },
    mode,                           // "edit" or "view"
    user: { id: userId, name: userName },
  };
  const body = `${b64url(header)}.${b64url(claims)}`;
  const signature = createHmac("sha256", SECRET).update(body).digest("base64url");
  return `${body}.${signature}`;
}

// e.g. with Express:
// app.get("/api/contracts/:id/editor-token", requireLogin, (req, res) => {
//   const contract = await contracts.get(req.params.id, req.user);
//   res.json({ token: mintSessionToken({
//     fileKey: `contract-${contract.id}`, fileName: contract.fileName,
//     fileUrl: contract.signedDownloadUrl(), version: contract.etag,
//     userId: req.user.id, userName: req.user.name,
//     mode: contract.canEdit(req.user) ? "edit" : "view" }) });
// });
```

Python:

```python
# server.py — the same token with PyJWT (pip install pyjwt)
import os, time, uuid
import jwt

APP_ID = os.environ["MROFFICE_APP_ID"]
SECRET = os.environ["MROFFICE_SECRET_KEY"]  # mro_sk_… (server only)

def mint_session_token(file_key, file_name, file_url, user_id, user_name, mode="edit", version=None):
    now = int(time.time())
    claims = {
        "iss": APP_ID,
        "aud": "mroffice-embed",
        "iat": now,
        "exp": now + 600,
        "jti": str(uuid.uuid4()),
        "file": {"key": file_key, "name": file_name, "url": file_url, "version": version},
        "mode": mode,
        "user": {"id": user_id, "name": user_name},
    }
    return jwt.encode(claims, SECRET, algorithm="HS256")
```

### 3. Open the editor in your page

```html
<div id="editor" style="height: 80vh"></div>
<script src="https://mroffice.ai/embed/v1/embed.js"></script>
<script>
  const editor = MROffice.open({
    container: "#editor",
    appId: "YOUR_APP_ID",                 // the editor starts loading while your server signs
    // Asked whenever a fresh token is needed: the first one, before the session
    // ends, after a reload, and by setMode() and setLocale().
    token: () => fetch("/api/contracts/42/editor-token").then((r) => r.json()).then((b) => b.token),
    locale: "en",
    theme: "light",                       // "dark" | "system"
    ui: { toolbar: "full" },              // "none" hides the ribbon
    onReady: (event) => console.log("open", event.document),
    onChange: (event) => console.log("modified", event.modified),
    onSave: (event) => console.log("saved version", event.version, event.downloadUrl),
    onError: (error) => console.error(error.code, error.hint ?? error.message),
  });
  document.querySelector("#save").onclick = () => editor.requestSave();
</script>
```

Or install the typed package:

```js
npm install mroffice-embed

import { open } from "mroffice-embed";

const editor = open({
  container: element,
  appId: "YOUR_APP_ID",
  token: ({ mode }) => getEditorToken(contractId, mode),   // your endpoint
  onSave: (saved) => { /* … */ },
  onConnectionChange: ({ online }) => setBanner(online ? null : "Reconnecting…"),
});
await editor.ready;
const saved = await editor.requestSave();   // { version, sha256, downloadUrl, … }
await editor.setMode("view");               // a fresh token from token({ mode: "view" })
await editor.setLocale("ja");               // reloads in Japanese, same document
await editor.destroy();
```

In React or Vue it is one component (Angular, Svelte and a Web Component too: see Framework components):

React:

```tsx
import { MROfficeEditor } from "mroffice-embed/react";

// your server's route that answers { token, appId, origin } (npx mroffice-embed init writes it)
<MROfficeEditor tokenUrl="/api/mroffice/session" style={{ height: "80vh" }} onSave={(saved) => console.log(saved.version)} />
```

Vue:

```vue
<script setup>
import { MROfficeEditor } from "mroffice-embed/vue";
</script>

<template>
  <MROfficeEditor token-url="/api/mroffice/session" style="height: 80vh" @save="(saved) => console.log(saved.version)" />
</template>
```

### Building on localhost

With Allow localhost on, your dev server shows the editor as it is. A file.local token needs no file server at all: the person (or your page, with openFile) opens a file from their computer. Every refused start, with its reason, is in the console's Events.

```js
// While you build: the console's "Allow localhost" lets any http://localhost:<port>
// (and http://127.0.0.1:<port>) page show the editor, so your dev server works as is.
// Open a file from your computer with a file.local token (no file server needed):
const token = await createSessionToken({
  appId, secretKey,
  file: { key: `dev-${Date.now()}`, local: true },   // the app must allow local files
  user: { id: "me", name: "Me" },
});
```
