# Embedded editor (/docs/guides/embedded-editor)

> Let your users edit a Druckling template inside your own product, in a white-label editor that you frame on your pages.

The embedded editor puts Druckling's template editor inside your product, so your users can change their own invoice, certificate or ticket layout without a Druckling account. Your backend creates a short-lived session for one template, your frontend shows it in an iframe, and the editor tells your page what happens over `postMessage`.

## How it works [#how-it-works]

1. **Once:** allow the origins of your app in **Settings › Embed**.
2. **When a user opens the editor:** your backend creates a session with `POST /v1/embed_sessions` and passes the returned `url` to that user's browser.
3. **In the browser:** your page mounts the `url` in an iframe, with `@druckling/embed` or a plain `<iframe>`.
4. **When the user signs out:** your backend revokes the session with `DELETE /v1/embed_sessions/{id}`.

A session reaches exactly one template: its draft, live previews and, if you allow it, publishing. Nothing else in your workspace is reachable with it.

## Plans [#plans]

Every plan can embed the editor. White-label and the assistant come with Pro and Business. Druck, Druckling's AI assistant, appears as a neutral "Assistant" in embedded editors, with no Druckling persona, so it fits your product:

| Plan | Embedded editor | Without "Powered by Druckling" | Assistant in the editor |
| --- | --- | --- | --- |
| Free | Yes | No | No |
| Starter | Yes | No | No |
| Pro | Yes | Yes | Yes |
| Business | Yes | Yes | Yes |

On Free and Starter the editor's header shows a small "Powered by Druckling" mark. Asking for the assistant on a plan without it isn't an error: the session is created without it, and its `permissions.assistant` is `false`. See [Plans and limits](/docs/concepts/plans-and-limits) for everything else the plans include.

## Before you start [#before-you-start]

- A **full-access** API key (`dr_test_…` while you build). Render-only keys can't create editor sessions. See [Authentication](/docs/authentication).
- A template to edit, for example the `invoice-standard` starter. It doesn't need to be published: the editor works on the draft.
- An owner or admin of the workspace to allow your origins (see [Team](/docs/guides/team)).

## 1. Allow your app's origins [#1-allow-your-apps-origins]

In **Settings › Embed › Allowed origins**, add every origin that will show the editor, for example `https://app.example.com`, and `http://localhost:5173` while you develop. Druckling only lets these origins frame the editor (with the CSP `frame-ancestors` directive), and the editor only exchanges messages with them.

- **Scheme, host and port only.** No path, query or fragment. A trailing slash is removed and the host is lowercased.
- **`https://` only**, except `http://localhost`, `http://127.0.0.1` and `http://[::1]` (with any port) for development.
- **Wildcards** cover subdomains: `https://*.example.com` matches `https://acme.example.com` but not `https://example.com`. Add the apex separately if you need it.
- **Up to 20 origins** per workspace. They apply to sessions created with test and live keys alike.
- **Only owners and admins** can add or remove origins. Members see the list read-only.
- **Removing an origin** takes effect on the next page load: from then on, browsers refuse to show the editor there.

Until the workspace allows at least one origin, creating a session with an API key fails with `409 invalid_state`.

<Callout type="info" title="Try it first">

The **Try it** section of **Settings › Embed** opens the embedded editor in the dashboard, exactly as your users will see it, in a 15-minute preview session. It doesn't need any allowed origin.

</Callout>

## 2. Create a session on your server [#2-create-a-session-on-your-server]

When a signed-in user opens the editor in your product, create a session from your backend and send its `url` to that user's browser. Never call the API from the browser: that would expose your API key.

The examples below are a `POST /api/template-editor` route in your own app. Run your usual sign-in check first, and keep the session `id` with the user's session so you can [revoke it](#4-revoke-the-session-on-sign-out) later.

```bash tab="cURL"
curl https://druckling-nine.vercel.app/v1/embed_sessions \
  -H "Authorization: Bearer $DRUCKLING_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "template": "invoice-standard",
    "permissions": { "publish": false, "assistant": true },
    "expires_in": 1800,
    "user": { "id": "user_42", "name": "Jane Doe" },
    "theme": { "mode": "light", "accent": "#0f766e" }
  }'
```

```ts tab="TypeScript" title="server.ts"
import express from "express";
import Druckling from "@druckling/sdk";

const app = express();
const druckling = new Druckling();

app.post("/api/template-editor", requireSignedInUser, async (req, res) => {
  const session = await druckling.embedSessions.create({
    template: "invoice-standard",
    permissions: { publish: false, assistant: true },
    expiresIn: 1800,
    user: { id: req.user.id, name: req.user.name },
    theme: { mode: "light", accent: "#0f766e" },
  });
  req.session.editorSessionId = session.id;
  res.set("Cache-Control", "no-store").json({ url: session.url });
});
```

```python tab="Python" title="app.py"
from flask import Flask, jsonify, session
from flask_login import current_user, login_required
from druckling import Druckling

app = Flask(__name__)
client = Druckling()

@app.post("/api/template-editor")
@login_required
def open_template_editor():
    editor = client.embed_sessions.create(
        template="invoice-standard",
        permissions={"publish": False, "assistant": True},
        expires_in=1800,
        user={"id": str(current_user.id), "name": current_user.name},
        theme={"mode": "light", "accent": "#0f766e"},
    )
    session["editor_session_id"] = editor.id
    response = jsonify(url=editor.url)
    response.headers["Cache-Control"] = "no-store"
    return response
```

```php tab="PHP" title="template-editor.php"
<?php
require __DIR__ . '/vendor/autoload.php';

use Druckling\Druckling;

session_start();
$user = requireSignedInUser();

$druckling = new Druckling();
$editor = $druckling->embedSessions->create(
    template: 'invoice-standard',
    permissions: ['publish' => false, 'assistant' => true],
    expiresIn: 1800,
    user: ['id' => (string) $user->id, 'name' => $user->name],
    theme: ['mode' => 'light', 'accent' => '#0f766e'],
);
$_SESSION['editor_session_id'] = $editor->id;

header('Content-Type: application/json');
header('Cache-Control: no-store');
echo json_encode(['url' => $editor->url]);
```

The SDKs read the key from `DRUCKLING_API_KEY`; see [SDKs](/docs/sdks) to install them. The API answers `201 Created` with the session:

```json title="Response"
{
  "id": "emb_8Qw2kLm3nP0aB1cD",
  "object": "embed_session",
  "url": "https://druckling-nine.vercel.app/embed/editor?session=emb_8Qw2kLm3nP0aB1cD#token=dr_embed_…",
  "template": "invoice-standard",
  "permissions": { "publish": false, "assistant": true },
  "user": { "id": "user_42", "name": "Jane Doe" },
  "theme": { "mode": "light", "accent": "#0f766e" },
  "status": "active",
  "expires_at": "2026-10-27T10:30:00.000Z",
  "revoked_at": null,
  "test_mode": true,
  "created_at": "2026-10-27T10:00:00.000Z"
}
```

<Callout type="warn" title="The url is a credential">

Whoever opens the `url` can edit the template until the session ends. It's returned only when the session is created (later responses have `url: null`). Send it to the signed-in user's browser only, and never log it, cache it or render it into a cacheable HTML page.

</Callout>

### Parameters [#parameters]

The [API reference](/docs/api-reference/embedded-editor/create) lists every field. These decide how the session behaves:

| Parameter | Behavior |
| --- | --- |
| `template` | Slug of the template to edit. An unknown slug answers `404 not_found`. |
| `permissions.publish` | Default `false`: the user edits the draft and someone on your team publishes it. With `true` the editor shows a **Publish** button. |
| `permissions.assistant` | Default `false`. With `true`, the AI assistant is offered on Pro and Business. Check `permissions.assistant` in the response to see whether it is. |
| `expires_in` | Seconds until the session ends, from `60` to `3600`. Default `1800` (30 minutes). |
| `user` | Your `id` for the user (required in the object) and an optional `name`. Shown in **Developers › Logs** and on the versions they publish. |
| `theme.mode` | `light` (default), `dark`, or `system` to follow the user's operating system. |
| `theme.accent` | Your brand color as `#rgb` or `#rrggbb`. See [Theming](#theming). |

### Errors [#errors]

| Status | Code | Why |
| --- | --- | --- |
| `400` | | The body is outside the documented limits, e.g. `expires_in: 7200` or `accent: "teal"`. |
| `401` | `unauthorized` | Missing, invalid or revoked API key. |
| `403` | `forbidden` | The key is render-only. Use a full-access key. |
| `404` | `not_found` | No template with that slug. |
| `409` | `invalid_state` | The workspace has no allowed origin yet. Add one in **Settings › Embed**. |
| `429` | `rate_limited` | More than 60 sessions a minute for the workspace. Create sessions when a user opens the editor, not on every page view. |

The SDKs raise these as typed errors (for example `ConflictError` for the `409`). See [Errors](/docs/concepts/errors) for the response format.

## 3. Show the editor in your frontend [#3-show-the-editor-in-your-frontend]

Fetch the `url` from your backend and mount it. The editor is a full editing surface with a blocks panel, the page canvas and a properties panel, so give it most of the viewport.

### With @druckling/embed [#with-drucklingembed]

`@druckling/embed` is a small, dependency-free browser helper. It creates the iframe, checks that every message comes from the editor, and gives you typed events and a `save()` method. It never sees your API key.

<Callout type="info" title="Not on npm yet">

`@druckling/embed` isn't published to npm yet. Get it from the Druckling source repository: either copy `src/integrations/embed/src/index.ts` and `protocol.ts` into your frontend, or pack the package and install the tarball.

```bash
git clone https://github.com/vulpery/druckling.git
cd druckling/src/integrations/embed
npm pack
cd /path/to/your-app
npm install /path/to/druckling-embed-0.1.0.tgz
```

The package ships TypeScript source. Bundlers that compile TypeScript dependencies, such as Vite, take it as is; in Next.js, add it to `transpilePackages`.

</Callout>

```ts title="template-editor.ts"
import { mountEditor } from "@druckling/embed";

const { url } = await fetch("/api/template-editor", { method: "POST" }).then((r) => r.json());

const editor = mountEditor({
  url,
  container: "#template-editor",
  height: "80vh",
  closeButton: true,
  onReady: ({ template, permissions, expiresAt }) => console.log(`Editing ${template.name} until ${expiresAt}`),
  onSaved: ({ revision }) => console.log(`Draft saved (revision ${revision})`),
  onPublished: ({ version }) => console.log(`Version ${version} is live`),
  onError: ({ code, message }) => console.warn(code, message),
  onClosed: () => editor.destroy(),
});
```

`mountEditor` takes these options:

<TypeTable
  type={{
    url: { type: "string", description: "The url your backend received from POST /v1/embed_sessions. Pass it unchanged; never build it in the browser.", required: true },
    container: { type: "HTMLElement | string", description: "The element the iframe goes into, or a CSS selector for it. Throws if nothing matches.", required: true },
    height: { type: "number | string", description: "Iframe height in pixels, or any CSS length. With the default, give the container a height.", default: "\"100%\"" },
    closeButton: { type: "boolean", description: "Show a Done button in the editor's header. Clicking it saves and fires closed.", default: "false" },
    title: { type: "string", description: "Accessible name of the iframe.", default: "\"Template editor\"" },
    onReady: { type: "(event) => void", description: "The editor is open on its template." },
    onSaved: { type: "(event) => void", description: "The draft was saved." },
    onPublished: { type: "(event) => void", description: "A new version was published from the editor." },
    onError: { type: "(event) => void", description: "Something went wrong or the session ended; see the error codes below." },
    onClosed: { type: "(event) => void", description: "The user clicked Done and their changes are saved." },
  }}
/>

It returns a handle:

| Member | Description |
| --- | --- |
| `iframe` | The `HTMLIFrameElement` it created. |
| `on(type, handler)` | Subscribes to an event. Returns a function that unsubscribes. |
| `save({ timeoutMs })` | Saves pending changes now, e.g. before you navigate away. Resolves with the `saved` event, rejects with an `Error` that has the `code` of the `error` event, or rejects after `timeoutMs` (default 15,000). |
| `destroy()` | Removes the iframe and stops listening. |

```ts
async function leaveEditor() {
  await editor.save();
  editor.destroy();
}
```

### Events [#events]

| Event | Payload | When |
| --- | --- | --- |
| `ready` | `template` (`id`, `slug`, `name`), `permissions` (`publish`, `assistant`), `expiresAt` | The editor opened its template. |
| `saved` | `revision`, `savedAt`, `requestId` | After every autosave, and in answer to `save()` (with its `requestId`). |
| `published` | `version`, `publishedAt` | The user published a new version (only if the session may publish). |
| `error` | `code`, `message`, `requestId` | See the codes below. |
| `closed` | | The user clicked **Done** and their changes are saved. |

Error codes:

| Code | Meaning | What to do |
| --- | --- | --- |
| `session_expired` | The session reached its `expires_at`. | Create a new session and mount it again. |
| `session_revoked` | You revoked the session. | Nothing, or create a new one if the user should continue. |
| `invalid_session` | The URL has no valid token, or the token doesn't belong to its `?session=`. | Create a new session and pass its `url` unchanged. |
| `template_unavailable` | The session's template was deleted. | Create a session for another template. |
| `load_failed` | The template couldn't be loaded. The editor offers **Try again**. | Retry, or mount a new session. |
| `save_failed` | Pending changes couldn't be saved yet, in answer to `save()` or **Done**. | Try again in a moment. |
| `publish_failed` | Publishing failed, e.g. because the draft has validation errors. | The editor shows why; the user can fix it and publish again. |

After `session_expired`, `session_revoked` or `invalid_session`, the editor shows a "session ended" screen and does nothing else.

### With a plain iframe [#with-a-plain-iframe]

You can also put the `url` in an iframe yourself. Set `src` from JavaScript after fetching it from your backend, so the token never ends up in your HTML.

```html title="Template editor"
<iframe
  id="template-editor"
  title="Template editor"
  style="width: 100%; height: 80vh; border: 0"
  allow="clipboard-write"
  referrerpolicy="origin"
></iframe>
```

```js title="template-editor.js"
const iframe = document.getElementById("template-editor");
const { url } = await fetch("/api/template-editor", { method: "POST" }).then((r) => r.json());
const editorOrigin = new URL(url).origin;

window.addEventListener("message", (event) => {
  if (event.origin !== editorOrigin || event.source !== iframe.contentWindow) return;
  const message = event.data;
  if (message?.source !== "druckling-embed" || message.protocol !== 1) return;

  if (message.type === "error" && message.code === "session_expired") showReopenButton();
});

iframe.addEventListener("load", () => {
  iframe.contentWindow.postMessage({ source: "druckling-embed", protocol: 1, type: "connect", closeButton: true }, editorOrigin);
});

iframe.src = url;
```

Every message carries `source: "druckling-embed"` and `protocol: 1`; the events are the ones listed above. Your page can send two commands:

- `connect`, with an optional `closeButton: true` for the **Done** button. Send it when the iframe loads.
- `save`, with an optional `requestId` (up to 100 characters). The editor answers with `saved` or `error` carrying the same `requestId`.

The editor only sends events once it knows which page frames it and that the page's origin is allowed. Most browsers report the framing page's origin to it; where they don't, it uses the referrer (hence `referrerpolicy="origin"`) or your `connect` message. Events from before that are held back and delivered once it's connected.

### Renew an expired session [#renew-an-expired-session]

Sessions can't be extended. When `session_expired` arrives, create a new session and mount it in place of the old one. The draft is saved as the user edits, so the new session opens where they left off.

```ts title="template-editor.ts"
import { mountEditor } from "@druckling/embed";

async function openEditor() {
  const { url } = await fetch("/api/template-editor", { method: "POST" }).then((r) => r.json());
  const editor = mountEditor({
    url,
    container: "#template-editor",
    height: "80vh",
    onError: ({ code }) => {
      if (code !== "session_expired") return;
      editor.destroy();
      void openEditor();
    },
  });
}

void openEditor();
```

If users tend to edit for longer, raise `expires_in` (up to an hour), or use `expiresAt` from the `ready` event to remind them before the session ends.

## 4. Revoke the session on sign-out [#4-revoke-the-session-on-sign-out]

Sessions end on their own at `expires_at`. To end one early, for example when the user signs out of your product, revoke it with the id you stored. The open editor reports `session_revoked` on its next request, such as the next autosave. Revoking twice is fine.

```bash tab="cURL"
curl -X DELETE https://druckling-nine.vercel.app/v1/embed_sessions/emb_8Qw2kLm3nP0aB1cD \
  -H "Authorization: Bearer $DRUCKLING_API_KEY"
```

```ts tab="TypeScript"
await druckling.embedSessions.revoke(req.session.editorSessionId);
```

```python tab="Python"
client.embed_sessions.revoke(session["editor_session_id"])
```

```php tab="PHP"
$druckling->embedSessions->revoke($_SESSION['editor_session_id']);
```

The response is the session with `status: "revoked"` and `url: null`. Revoke with a full-access key of the same mode as the key that created the session; a key of the other mode gets `404`. See [Revoke an embedded editor session](/docs/api-reference/embedded-editor/revoke).

## What a session can do [#what-a-session-can-do]

An editor session works on its own template only:

- **Read** the template and its draft.
- **Edit** the draft. Changes save automatically and never affect renders until a new version is published.
- **Preview** the page live, and open a **Test PDF** of the draft in a new tab. Test PDFs don't create documents.
- **Publish** a new version, only with `permissions.publish: true`. From then on, API requests for `version: "latest"` render it. Pin a `version` in your render requests if you want to review changes first.
- **Use the AI assistant**, only with `permissions.assistant: true` on Pro or Business. In the embedded editor the assistant works on that template only and doesn't take image attachments.

It can't open other templates (even ones that exist), documents, API keys, webhooks, billing, team or workspace settings, and it can't create sessions. The editor has no dashboard navigation, so there's no way out of the template.

Without `permissions.publish`, your users' changes stay in the draft until someone on your team publishes it in the dashboard. Druckling sends no webhook when a template is published; the `published` event is how your page finds out.

## Security model [#security-model]

- **The token travels in the URL fragment.** The `url` carries the session token after `#token=`, and browsers never send the fragment to any server. The editor reads it once, removes it from its address and history, keeps it in memory and sends it as an `Authorization` header. Druckling stores only a SHA-256 hash of the token.
- **The session id isn't a secret.** `?session=emb_…` only picks the page's `frame-ancestors`. A token that doesn't belong to that session is rejected.
- **Framing is restricted.** The editor page answers with `Content-Security-Policy: frame-ancestors 'self'` plus your allowed origins (`'self'` is Druckling's own dashboard, for the preview). An unknown session gets `frame-ancestors 'none'`.
- **Messages go to your origin only.** The editor posts messages to the exact origin of the framing page, never `*`, and only once that origin is allowed. It accepts commands only from the parent window at that origin. Check `event.origin` and `event.source` the same way on your side, or let `@druckling/embed` do it.
- **No cookies.** The editor doesn't use cookies, so browsers that block third-party cookies show it as well. Requests carrying an editor token reach only the editor's own operations, whatever cookies come with them.
- **Short-lived by default.** 30 minutes unless you set `expires_in`, at most an hour, and revocable at any time.
- **Your API key stays on your server.** Create sessions from your backend after your own sign-in check, and hand the `url` only to the user it's for.

## Logs and version history [#logs-and-version-history]

**Developers › Logs** shows what your users do in the editor:

- `POST /v1/embed_sessions` and `DELETE /v1/embed_sessions/{id}` appear with the API key that made them and "for" the user you passed.
- Requests from the editor itself (opening the session, saving the draft, publishing, test PDFs and any request that failed) appear with **Embedded editor** in the API key column and "for" the user's `name` (or `id`), or the session id when you didn't pass a `user`. Successful template loads and previews aren't logged.

Published versions record who published them as `embed:` plus your user's `id` (for example `embed:user_42`), or plus the session id without a `user`. You see it in the template's version history.

## Test and live keys [#test-and-live-keys]

A session takes the mode of the key that created it, shown as `test_mode`. Its requests appear in **Developers › Logs** when the dashboard's **Test mode** matches.

<Callout type="warn" title="Templates are shared between modes">

Test mode separates documents and usage, not templates. A session created with a `dr_test_…` key edits the same template your live renders use, and with `permissions.publish: true` it publishes real versions. Experiment on a copy of the template, or keep publishing off while you test.

</Callout>

See [Test mode](/docs/concepts/test-mode) for what else test keys change.

## Theming [#theming]

Each session can match the brand of the customer it's for:

- `theme.mode`: `light` (default), `dark`, or `system`, which follows the user's operating system and switches live when they change it.
- `theme.accent`: a hex color that becomes the editor's primary color: buttons, focus rings, selections and highlights. Text on it is black or white, whichever reads better. `#0f766e` and `#0F766E` are the same color, and `#abc` is stored as `#aabbcc`.

Without an accent, the editor keeps Druckling's own colors.

## Limits [#limits]

| Limit | Value |
| --- | --- |
| Session length | 30 minutes by default, 60 seconds to 1 hour |
| New sessions | 60 a minute per workspace |
| Allowed origins | 20 per workspace |
| Requests from one editor session (saves, previews) | 600 a minute |
| Assistant turns in one editor session | 10 a minute |

## Troubleshooting [#troubleshooting]

<Accordions>
<Accordion title="The iframe is blank, or the browser refuses to show it">

The browser blocked the frame because of `frame-ancestors`. Check that:

- The exact origin of your page is in **Settings › Embed**: scheme, host and port. `https://www.example.com` and `https://example.com` are different, and `https://*.example.com` doesn't cover `https://example.com`.
- You pass the `url` unchanged. Without its `?session=` the page can't be framed anywhere.
- The session is recent. Sessions are deleted a day or two after they expire, and their URLs can't be framed after that. Create a new one.
- Your own Content Security Policy allows the frame, e.g. `frame-src https://druckling-nine.vercel.app`.

</Accordion>
<Accordion title="Creating a session fails with 409 invalid_state">

The workspace has no allowed origin. An owner or admin adds one in **Settings › Embed**.

</Accordion>
<Accordion title="Creating a session fails with 403 forbidden">

The API key is render-only. Create a full-access key in **Developers › API keys**.

</Accordion>
<Accordion title="The editor says the link isn't valid">

The token is missing or doesn't match the session in the URL. Something between your backend and the iframe dropped the `#token=…` fragment or changed the URL, for example a redirect or a router that rewrites links. Pass the `url` exactly as the API returned it.

</Accordion>
<Accordion title="No events reach my page">

- Compare `event.origin` with Druckling's origin (`new URL(url).origin`), not your own.
- Your page's origin must be allowed in **Settings › Embed**; the editor never posts to other origins.
- With a plain iframe, set `referrerpolicy="origin"` and send the `connect` command when the iframe loads.

</Accordion>
<Accordion title="There's no Publish button or no assistant">

The editor shows **Publish** only with `permissions.publish: true`, and the assistant only with `permissions.assistant: true` on Pro or Business. The `ready` event and the create response tell you what the session got.

</Accordion>
<Accordion title="save() rejects after 15 seconds">

The editor didn't answer, usually because it hasn't finished loading or its session already ended. Wait for `ready` before calling `save()`.

</Accordion>
</Accordions>

## Next steps [#next-steps]

<Cards>
  <Card title="Create an embedded editor session" href="/docs/api-reference/embedded-editor/create">
    Every field of the request and the response.
  </Card>
  <Card title="Templates" href="/docs/concepts/templates">
    Drafts, published versions and how renders pick a version.
  </Card>
  <Card title="Webhooks" href="/docs/guides/webhooks">
    Get notified when documents rendered from your users' templates are ready.
  </Card>
</Cards>
