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
- Once: allow the origins of your app in Settings › Embed.
- When a user opens the editor: your backend creates a session with
POST /v1/embed_sessionsand passes the returnedurlto that user's browser. - In the browser: your page mounts the
urlin an iframe, with@druckling/embedor a plain<iframe>. - 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
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 for everything else the plans include.
Before you start
- A full-access API key (
dr_test_…while you build). Render-only keys can't create editor sessions. See Authentication. - A template to edit, for example the
invoice-standardstarter. 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).
1. Allow your app's 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, excepthttp://localhost,http://127.0.0.1andhttp://[::1](with any port) for development.- Wildcards cover subdomains:
https://*.example.commatcheshttps://acme.example.combut nothttps://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.
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.
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 later.
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" }
}'The SDKs read the key from DRUCKLING_API_KEY; see SDKs to install them. The API answers 201 Created with the session:
{
"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"
}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.
Parameters
The API reference 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. |
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 for the response format.
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
@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.
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.
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.tgzThe package ships TypeScript source. Bundlers that compile TypeScript dependencies, such as Vite, take it as is; in Next.js, add it to transpilePackages.
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:
Prop
Type
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. |
async function leaveEditor() {
await editor.save();
editor.destroy();
}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
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.
<iframe
id="template-editor"
title="Template editor"
style="width: 100%; height: 80vh; border: 0"
allow="clipboard-write"
referrerpolicy="origin"
></iframe>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 optionalcloseButton: truefor the Done button. Send it when the iframe loads.save, with an optionalrequestId(up to 100 characters). The editor answers withsavedorerrorcarrying the samerequestId.
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
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.
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
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.
curl -X DELETE https://druckling-nine.vercel.app/v1/embed_sessions/emb_8Qw2kLm3nP0aB1cD \
-H "Authorization: Bearer $DRUCKLING_API_KEY"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.
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 forversion: "latest"render it. Pin aversionin your render requests if you want to review changes first. - Use the AI assistant, only with
permissions.assistant: trueon 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
- The token travels in the URL fragment. The
urlcarries 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 anAuthorizationheader. Druckling stores only a SHA-256 hash of the token. - The session id isn't a secret.
?session=emb_…only picks the page'sframe-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 getsframe-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. Checkevent.originandevent.sourcethe same way on your side, or let@druckling/embeddo 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
urlonly to the user it's for.
Logs and version history
Developers › Logs shows what your users do in the editor:
POST /v1/embed_sessionsandDELETE /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(orid), or the session id when you didn't pass auser. 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
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.
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.
See Test mode for what else test keys change.
Theming
Each session can match the brand of the customer it's for:
theme.mode:light(default),dark, orsystem, 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.#0f766eand#0F766Eare the same color, and#abcis stored as#aabbcc.
Without an accent, the editor keeps Druckling's own colors.
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 |