Headless Live Preview Architecture — Real-Time Visual Editing & Iframe Sync
Enterprise headless live preview architecture: cryptographic handshake, postMessage bridge, zero-layout-shift SSR drafts, and visual editing for SvelteKit & Next.js.
On this page
SveltyCMS implements an Enterprise Handshake Protocol for Live Preview. Signed preview tokens establish draft sessions; a postMessage bridge keeps the CMS editor and frontend preview in sync.
Live preview is delivered by the Editable Website & Live Preview plugin — a premium marketplace extension (€14.99, 14-day trial). The CMS core, APIs, and optional SvelteKit Site Starter work without the plugin; the plugin adds the Live Preview tab, bidirectional iframe sync, and click-to-edit.
Deployment Options
| Approach | Best for | Live Preview plugin |
|---|---|---|
Site Starter (routes/(site)) |
Same-repo SvelteKit, zero extra dev server | Recommended — previews same-origin / |
| External SvelteKit / Astro / Next.js | Production decoupled frontends | Required for iframe tab; implement protocol in your theme |
| API-only headless | Mobile apps, static exports | Optional — no iframe UI without the plugin |
Architecture Overview
This “Handshake” architecture solves three critical enterprise challenges:
| Challenge | Solution |
|---|---|
| Security | Prevents unauthorized access to draft content via a shared Secret Token |
| Stability | Sets Server-Side Cookies to ensure A/B tests and draft modes work with SSR (no layout shift) |
| Reliability | Initializes the session on the correct domain, bypassing 3rd-party cookie restrictions in iframes |
1. CMS Configuration
Enable the premium plugin
- Purchase or start the 14-day trial for Editable Website & Live Preview on marketplace.sveltycms.com
- Enable the plugin for your tenant (Config → Plugins)
- Add
plugins: ["editable-website"]on collections that should show the Live Preview tab
Collection livePreview pattern
Use a URL pattern (relative for same-origin site starter, absolute for external frontends):
// config/collections/pages.ts — Website Starter preset
export default {
_id: "pages",
livePreview: "/{slug}?lang={lang}",
plugins: ["editable-website"],
fields: [/* ... */],
};
| Placeholder | Resolves to |
|---|---|
{slug} |
Entry slug (home → / on site starter) |
{lang} |
Active content language |
{_id} / {id} |
Entry database id |
For external domains:
livePreview: "https://www.example.com/{slug}?lang={lang}",
System settings
PREVIEW_SECRET(private) — HMAC signing key forpreview_token(fail-closed if missing)PREVIEW_BASE_URL(public, optional) — Origin for relativelivePreviewpaths. Blank falls through toHOST_PRODHOST_PROD/HOST_DEV— Base URL whenPREVIEW_BASE_URLis blank andlivePreviewis a relative pathSITE_STARTER_ENABLED(public, defaultfalse) — Toggle the in-repo site starter at/. The Website Starter preset sets it totrue.
2. Frontend Implementation
Built-in: SvelteKit Site Starter
If you use the Site Starter, these routes are already implemented:
| Route | Purpose |
|---|---|
POST /api/preview/authorize |
CMS generates signed previewUrl (plugin calls this) |
GET /api/preview |
Validates token, sets cms_draft_mode cookie, redirects |
routes/(site)/* |
Public pages with createSitePreviewBridge() |
External frontends: handshake endpoint
For decoupled SvelteKit/Astro/Next apps, add a preview route that validates the signed token (or legacy shared secret) and sets draft cookies.
Example: src/routes/api/preview/+server.ts
import { redirect, error } from "@sveltejs/kit";
import { previewService } from "$lib/preview"; // wrap SveltyCMS validateToken
export async function GET({ url, cookies }) {
const token = url.searchParams.get("preview_token");
const slug = url.searchParams.get("slug") || "/";
if (!token) throw error(400, "Missing preview_token");
const validated = previewService.validateToken(token);
if (!validated.valid) throw error(401, "Invalid or expired token");
cookies.set("cms_draft_mode", "true", {
path: "/",
httpOnly: true,
sameSite: "none",
secure: true,
maxAge: 60 * 60,
});
throw redirect(307, slug);
}
Middleware Integration (hooks.server.ts)
If your frontend uses the SveltyCMS Middleware (handleApiRequests.ts) to guard /api/* routes, you must whitelist the preview endpoint.
Since the CMS iframe might not share the user’s login session (especially in cross-domain multi-tenancy), this endpoint relies on the Secret Token for security, not the User Session.
Update src/databases/auth/apiPermissions.ts or your whitelist logic:
// Allow public access to the preview endpoint
export const API_PERMISSIONS = {
// ... existing permissions ...
"api:preview": ["*"], // Allow all (guarded by Secret inside the endpoint)
};
Or update handleApiRequests.ts logic:
function isPublicApiRoute(pathname: string, method?: string): boolean {
// ... existing checks ...
// Allow Handshake Endpoint
if (pathname === "/api/preview") return true;
return false;
}
3. Data Fetching (Draft Mode)
Your page load functions should check for the cookie set by the handshake.
// src/routes/posts/[slug]/+page.server.ts
export const load = async ({ cookies, params }) => {
const isDraft = cookies.get("cms_draft_mode") === "true";
const variant = cookies.get("ab_test_variant") || "A";
// Fetch from CMS
const post = await cms.getPost(params.slug, {
draft: isDraft, // Fetch draft if cookie exists
variant: variant,
});
return { post };
};
4. Real-Time Updates (postMessage Protocol v1.2)
After SSR load, the frontend and CMS communicate via postMessage. Types live in src/plugins/editable-website/types.ts.
| Message | Direction | Purpose |
|---|---|---|
svelty:init |
Frontend → CMS | Handshake ready |
svelty:update |
CMS → Frontend | Push entry data on every edit |
svelty:field:click |
Frontend → CMS | Click-to-edit — focus CMS field |
svelty:field:select |
CMS → Frontend | Highlight field in preview |
svelty:save |
Frontend → CMS | Merge visual edits into entry form |
svelty:document:update |
Frontend → CMS | Targeted field update (svedit-ready) |
svelty:edit-mode |
CMS → Frontend | Toggle visual editing |
svelty:navigate |
Frontend → CMS | Link click inside the preview |
Frontend helper (framework-agnostic)
import { createLivePreviewListener } from "@utils/preview";
// Site starter uses createSitePreviewBridge() for bidirectional save
const { destroy } = createLivePreviewListener({
onUpdate: (data) => {
/* merge into page state */
},
visualEditing: true,
});
Mark editable elements with data-svelty-field="fieldName" matching CMS db_fieldName values.
Bridge hardening (2026-11)
The preview tab now behaves like a production editing surface, not a demo:
| Behaviour | What changed |
|---|---|
| Split Canvas sync | Both iframes (desktop + mobile) receive every svelty:update / svelty:edit-mode. Previously only the desktop frame was posted to. |
| Coalesced pushes | Form edits are pushed once per 60 ms burst (trailing) instead of once per keystroke; a pending push is flushed on unmount. |
| Reverse highlighting | Focusing a CMS field posts svelty:field:select; the frontend scrolls to and highlights the matching [data-svelty-field] (the site bridge already handled it). |
| Locale/target refresh | Changing the content language, livePreview pattern or tenant re-authorizes the preview URL; previously only _id/slug changes did. |
| Protocol check | A major-version mismatch between site bridge and CMS raises a warning toast; legacy bridges without a version are accepted. |
| Recovery | Authorization failures show a retry panel with the HTTP status instead of an endless spinner. |
| Origin hardening | localhost origins are accepted only in dev; postMessage never falls back to "*". |
| Navigation feedback | A preview link click (svelty:navigate) answers with a toast instead of failing silently. |
| Autosave / publish | Preview edits can auto-save (debounced 900 ms) or publish in one click. Both call the normal saveEntry lane, so the publication workflow, required-field checks and audit hooks still run. |
| Block palette | In preview the site starter shows a Blocks toolbar: add hero / paragraph / CTA / image, move a block up or down, delete it, and flip paragraph ↔ hero ↔ CTA. Changes go through the same document update and autosave/publish path. |
| Media on page | An image block accepts a drag-drop or file-picker upload (through /api/media/upload, so variants and thumbnails still run server-side) and stores a focal point applied with object-position — set by click or arrow keys. |
| Mobile edit mode | A bottom pill toggles the preview between editing and read-only; hold it (600 ms) to switch without an accidental tap. Read-only frames still receive document updates. |
| Draft-scoped AI loop | WebMCP get_live_preview_url mints the same signed URL the preview tab uses, so an agent can write a draft (update_entry, draft-forced) and inspect the rendered result without a rebuild. |
Where this sits against the market
The dashboard at /plugin/editable-website/competitive renders this same matrix from
src/plugins/editable-website/capabilities.ts (weighted bars: yes = 1, partial = 0.5,
n/a excluded), so the docs and the UI cannot drift apart.
| Capability | SveltyCMS | Payload / Directus / Strapi | Editable.website |
|---|---|---|---|
| Signed preview token + draft SSR | Yes | Yes | n/a (no admin) |
| Bidirectional field focus / highlight | Yes | Partial | Yes |
| On-page inline editing | Yes — Svedit (site starter) | Yes (visual editor) | Yes (core) |
| Desktop / tablet / mobile / split canvas | Yes | Yes | Yes |
| Instant publish without a rebuild | Yes — one-click Publish (autosave optional) | No | Yes |
| Block insert / reorder / layout flip on page | Yes | Yes | Yes |
| Drag-drop media + focal point on page | Yes | Partial | Yes |
| Mobile drag-hold edit mode | Yes | n/a | Yes |
| MCP / AI editing of the live page | Yes — draft-only writes + signed draft URL | Partial | Yes |
Comparisons reflect each vendor’s public documentation as of November 2026; re-check the current release before citing them externally.
Still open (honest list): free-text caret editing outside a structured block, inline
editing inside the split-canvas mobile frame (it is a preview surface), and a per-tool
AI diff/undo trail. Every one of these is listed in OPEN_GAPS and rendered by the
overview dashboard.
5. Performance Optimization: Deferred Rendering
In 2026, SveltyCMS implemented Deferred Rendering to maximize Admin UI performance.
- Lazy Handshake: The preview iframe and authorized URL handshake are deferred until the user first clicks the “Live Preview” tab. This saves significant CPU and network resources on initial page loads.
- Dormant State: When a user switches away from the Live Preview tab, the iframe remains mounted but enters a “Dormant” (paused) state. This ensures that switching back to the preview is instantaneous without re-triggering the handshake.
- Manual Override: A manual “Initialize Preview Now” button is available if an editor needs to force-start the preview before switching tabs.
6. Enterprise Considerations
A/B Testing Stability
This architecture is superior for A/B testing because the variant is established via Cookie before the page renders.
| Approach | Behavior |
|---|---|
| Without Handshake | ?variant=B query param. If the user clicks a link, the param is lost, and they might flip back to Variant A. |
| With Handshake | The cookie persists. The user stays in Variant B for the entire session. |
Cache Control & Treeshaking
- Headers: The handshake endpoint should set
Cache-Control: no-storeto prevent CDN caching of the redirect. - Optimization: The preview logic is isolated in
/api/preview. It adds zero JavaScript bundle size to your actual production pages.
Comparison
| Feature | Direct URL (?preview=true) |
API Handshake (/api/preview) |
|---|---|---|
| Security | ❌ Low (Guessable) | ✅ High (Token guarded) |
| Multi-Tenant Cookies | ❌ Blocked by Safari | ✅ Works (First-party context) |
| A/B Consistency | ⚠️ Query Param based | ✅ Cookie based (Session sticky) |
| Setup Effort | Low | Medium (One-time endpoint setup) |
Use the API Handshake method for all production deployments.
Related Documentation
- SvelteKit Site Starter — Optional in-repo public frontend
- Editable Website Plugin — Premium live preview (€14.99)
- fields Component — Entry editor with Live Preview tab
- Unified Error Handling — API error handling patterns
- Widget System Overview — Widget architecture