Implement SvelteKit with headless CMS live preview where the CMS loads the site in an iframe. Use window.postMessage to send draft content from the CMS to the SvelteKit app, applying overrides to the store state instantly without page reload.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Implementing SvelteKit live preview with postMessage
Here's a minimal SvelteKit setup where the app fetches published content on the server, uses a store to hold content, and updates that store instantly when receiving draft updates via window.postMessage from a CMS loaded in a parent iframe.
src/lib/stores/content.ts
ts
import { writable, derived } from 'svelte/store';
const published = writable(null);
const preview = writable({});
export const pageContent = derived([published, preview], ([$published, $preview]) => {
if (!$published) return null;
return { ...$published, ...$preview };
});
export function setPublished(data) {
published.set(data);
}
export function applyPreview(data) {
preview.set(data);
}
export function clearPreview() {
preview.set({});
}
src/routes/+page.server.ts
ts
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ fetch, params }) => {
// Simulate fetching published content from CMS by slug
const slug = params.slug ?? 'example-post';
// Replace below with real CMS API in production
const post = {
title: 'Published Title',
body: '<p>This is the published post content.</p>',
};
return { post };
};
src/routes/+page.svelte
svelte
<script lang="ts">
import { onMount } from 'svelte';
import { pageContent, setPublished, applyPreview, clearPreview } from '$lib/stores/content';
export let data;
const allowedOrigins = ['https://cms.example.com']; // Set your CMS origin here
onMount(() => {
setPublished(data.post);
const handleMessage = (event: MessageEvent) => {
if (!allowedOrigins.includes(event.origin)) return;
const message = event.data;
if (message?.type === 'preview') {
applyPreview(message.data);
} else if (message?.type === 'clear-preview') {
clearPreview();
}
};
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
});
</script>
<svelte:head>
<title>{$pageContent?.title ?? 'Loading...'}</title>
</svelte:head>
<h1>{$pageContent?.title}</h1>
<div>{@html $pageContent?.body}</div>
CMS preview sender snippet (to run in the CMS parent page)
js
// Assume the SvelteKit site is loaded in an iframe with id 'preview-frame'
const iframe = document.getElementById('preview-frame');
const draftContent = {
title: 'Draft Preview Title',
body: '<p>This is the draft content for live preview.</p>',
};
// Replace targetOrigin with your SvelteKit site URL
iframe.contentWindow.postMessage({ type: 'preview', data: draftContent }, 'https://your-sveltekit-site.com');
// To clear preview overrides:
// iframe.contentWindow.postMessage({ type: 'clear-preview' }, 'https://your-sveltekit-site.com');
This setup allows the CMS to send draft content via postMessage to the SvelteKit app running in the iframe, instantly updating the visible page content without a reload by overriding the store’s preview data.
Make sure to adjust allowedOrigins and postMessage target origins for proper security and origin checks in production.
Below is a minimal end‑to‑end example of wiring up a SvelteKit app to receive draft/preview content from a headless CMS that loads the site in an <iframe>, and applying those overrides live via window.postMessage without a page reload.
1) Svelte store to hold published + preview overrides
src/lib/stores/content.ts
ts
import { writable, derived } from 'svelte/store';
type Content = Record<string, any>;
// Published content from your CMS (e.g. fetched in the load function)
const published = writable<Content>({});
// Preview overrides coming from the CMS via postMessage
const preview = writable<Content>({});
// The content your components will render = published with preview overriding
export const content = derived([published, preview], ([$pub, $prev]) => ({
...$pub,
...$prev
}));
export function setPublished(data: Content) {
published.set(data);
}
export function setPreview(data: Content) {
// Replace or merge, depending on your needs
preview.set(data);
}
export function clearPreview() {
preview.set({});
}
2) Server load fetching published content
src/routes/+page.server.ts
ts
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ fetch }) => {
// Replace with your headless CMS API endpoint and parameters
const res = await fetch('https://cms.example.com/api/pages/home');
const data = await res.json();
return {
published: data
};
};
3) Page component that subscribes to the store and listens for postMessage
src/routes/+page.svelte
svelte
<script lang="ts">
import { onMount } from 'svelte';
import { content, setPublished, setPreview, clearPreview } from '$lib/stores/content';
export let data: { published: any };
const allowedOrigins = [
'https://cms.example.com', // your CMS origin
'http://localhost:3000' // for local dev (if needed)
];
onMount(() => {
// Hydrate published content
setPublished(data.published);
const handler = (event: MessageEvent) => {
// Basic origin check
if (!allowedOrigins.includes(event.origin)) return;
if (!event.data || typeof event.data !== 'object') return;
const { type, payload } = event.data;
if (type === 'preview') {
setPreview(payload);
} else if (type === 'clear-preview') {
clearPreview();
}
};
window.addEventListener('message', handler);
return () => window.removeEventListener('message', handler);
});
</script>
<svelte:head>
<title>{$content?.title ?? 'Loading…'}</title>
</svelte:head>
<main>
<h1>{$content?.title}</h1>
<div>{@html $content?.body}</div>
</main>
4) CMS side: send draft content to the iframe
Wherever your CMS renders the preview iframe (e.g. an admin page):
html
<!-- The SvelteKit site is loaded here -->
<iframe
id="preview-frame"
src="https://your-sveltekit-site.com/"
style="width:100%;height:80vh;border:1px solid #ccc;"
></iframe>
<!-- Example controls to modify draft content -->
<input id="draft-title" placeholder="Draft title">
<textarea id="draft-body" placeholder="Draft body"></textarea>
<button id="send-preview">Send preview</button>
<button id="clear-preview">Clear preview</button>
<script>
const iframe = document.getElementById('preview-frame');
document.getElementById('send-preview').addEventListener('click', () => {
const title = (document.getElementById('draft-title') as HTMLInputElement).value;
const body = (document.getElementById('draft-body') as HTMLTextAreaElement).value;
iframe.contentWindow?.postMessage(
{ type: 'preview', payload: { title, body } },
'https://your-sveltekit-site.com'
);
});
document.getElementById('clear-preview').addEventListener('click', () => {
iframe.contentWindow?.postMessage(
{ type: 'clear-preview' },
'https://your-sveltekit-site.com'
);
});
</script>
How it works
The SvelteKit page fetches published content in load and stores it in published.
The CMS embeds the SvelteKit site in an <iframe>.
As the editor changes draft data, the CMS calls iframe.contentWindow.postMessage({ type: 'preview', payload: { … } }, 'https://your-site').
The SvelteKit app listens for message events, validates the origin, and calls setPreview(payload).
The derived content store merges published + preview, so the UI updates instantly without a full page reload.
A clear-preview message resets the preview overrides.
This pattern decouples SSR/published data from live draft changes and is robust for headless CMS live previews.