This is a comprehensive request for implementing SvelteKit with a headless CMS that has live preview functionality. Let me break down what's needed:
- A SvelteKit application that can receive messages via
window.postMessage
- A way to override store state with draft content from the CMS
- A CMS interface that loads the SvelteKit site in an iframe
- Real-time preview updates without page reloads
- Proper communication between the parent window (CMS) and iframe (SvelteKit app)
I'll create:
- SvelteKit store setup for managing content
- A message handler in SvelteKit for receiving CMS data
- A CMS interface that sends preview data
- Example pages and components
- Proper type safety with TypeScript
- Security considerations
Let me create a comprehensive solution:
SvelteKit + Headless CMS Live Preview System
I'll build a complete live preview system where the CMS sends draft content to a SvelteKit app via postMessage.
1. SvelteKit Store Setup
// src/lib/stores/preview.ts
import { writable, derived } from 'svelte/store';
export interface PageContent {
id: string;
title: string;
slug: string;
content: string;
metadata?: Record<string, unknown>;
seo?: {
metaDescription: string;
keywords: string[];
};
}
export interface PreviewState {
isPreviewMode: boolean;
overrides: Partial<PageContent>;
isDirty: boolean;
lastUpdated: number;
}
// Main preview store
export const previewStore = writable<PreviewState>({
isPreviewMode: false,
overrides: {},
isDirty: false,
lastUpdated: 0
});
// Derived store for current page content
export const currentPageContent = derived(
previewStore,
($preview) => $preview.overrides
);
// Content merge logic
export function mergeContent(
original: PageContent,
overrides: Partial<PageContent>
): PageContent {
return Object.assign({}, original, overrides);
}
// Store helper functions
export const previewApi = {
setPreviewMode: (enabled: boolean) => {
previewStore.update(state => ({
...state,
isPreviewMode: enabled
}));
},
updateOverrides: (overrides: Partial<PageContent>) => {
previewStore.update(state => ({
...state,
overrides: Object.assign({}, state.overrides, overrides),
isDirty: true,
lastUpdated: Date.now()
}));
},
clearOverrides: () => {
previewStore.update(state => ({
...state,
overrides: {},
isDirty: false
}));
},
resetStore: () => {
previewStore.set({
isPreviewMode: false,
overrides: {},
isDirty: false,
lastUpdated: 0
});
}
};
2. Message Handler Hook
// src/lib/hooks/usePreviewMessages.ts
import { onMount } from 'svelte';
import { previewStore, previewApi } from '$lib/stores/preview';
import type { PageContent } from '$lib/stores/preview';
interface PreviewMessage {
type: 'PREVIEW_INIT' | 'PREVIEW_UPDATE' | 'PREVIEW_CLEAR' | 'PING' | 'ERROR';
payload?: Partial<PageContent> | { message: string };
}
interface MessageResponse {
type: 'PONG' | 'ACK' | 'ERROR';
status: 'success' | 'error';
data?: unknown;
}
// Allowed CMS origins (configure in production)
const ALLOWED_ORIGINS = process.env.VITE_CMS_ORIGINS?.split(',') || [
'http://localhost:3000',
'http://localhost:5173'
];
// Security validator
function isMessageAllowed(origin: string, message: PreviewMessage): boolean {
// Check origin
if (!ALLOWED_ORIGINS.includes(origin)) {
console.warn(`[Preview] Blocked message from unauthorized origin: ${origin}`);
return false;
}
// Validate message structure
const validTypes = ['PREVIEW_INIT', 'PREVIEW_UPDATE', 'PREVIEW_CLEAR', 'PING', 'ERROR'];
if (!validTypes.includes(message.type)) {
console.warn(`[Preview] Invalid message type: ${message.type}`);
return false;
}
return true;
}
// Validate content to prevent XSS
function sanitizeContent(content: Partial<PageContent>): Partial<PageContent> {
const sanitized: Partial<PageContent> = {};
if (content.id) sanitized.id = String(content.id).slice(0, 100);
if (content.title) sanitized.title = String(content.title).slice(0, 255);
if (content.slug) sanitized.slug = String(content.slug).slice(0, 255);
// Note: content.content should be sanitized by your HTML renderer
if (content.content) sanitized.content = content.content;
if (content.metadata) sanitized.metadata = content.metadata;
if (content.seo) {
sanitized.seo = {
metaDescription: String(content.seo.metaDescription).slice(0, 160),
keywords: Array.isArray(content.seo.keywords)
? content.seo.keywords.slice(0, 10).map(k => String(k).slice(0, 50))
: []
};
}
return sanitized;
}
export function usePreviewMessages() {
onMount(() => {
// Signal readiness to parent CMS
if (window.parent !== window) {
window.parent.postMessage(
{ type: 'PREVIEW_READY', version: '1.0' },
'*'
);
}
const handleMessage = (event: MessageEvent<PreviewMessage>) => {
const { data, origin } = event;
// Security check
if (!isMessageAllowed(origin, data)) {
const response: MessageResponse = {
type: 'ERROR',
status: 'error',
data: { message: 'Unauthorized message' }
};
window.parent.postMessage(response, '*');
return;
}
let response: MessageResponse;
try {
switch (data.type) {
case 'PREVIEW_INIT':
// Initialize preview mode with full content
if (data.payload) {
const sanitized = sanitizeContent(data.payload);
previewApi.setPreviewMode(true);
previewApi.updateOverrides(sanitized);
response = {
type: 'ACK',
status: 'success',
data: { message: 'Preview initialized' }
};
}
break;
case 'PREVIEW_UPDATE':
// Update specific fields with debouncing
if (data.payload) {
const sanitized = sanitizeContent(data.payload);
previewApi.updateOverrides(sanitized);
response = {
type: 'ACK',
status: 'success',
data: { message: 'Preview updated', timestamp: Date.now() }
};
}
break;
case 'PREVIEW_CLEAR':
// Clear all overrides
previewApi.clearOverrides();
response = {
type: 'ACK',
status: 'success',
data: { message: 'Preview cleared' }
};
break;
case 'PING':
// Health check
response = {
type: 'PONG',
status: 'success',
data: { timestamp: Date.now() }
};
break;
default:
response = {
type: 'ERROR',
status: 'error',
data: { message: 'Unknown message type' }
};
}
} catch (error) {
response = {
type: 'ERROR',
status: 'error',
data: { message: error instanceof Error ? error.message : 'Unknown error' }
};
}
// Send response back
window.parent.postMessage(response, '*');
};
window.addEventListener('message', handleMessage);
return () => {
window.removeEventListener('message', handleMessage);
};
});
}
3. SvelteKit Layout with Preview Hook
<!-- src/routes/+layout.svelte -->
<script lang="ts">
import { usePreviewMessages } from '$lib/hooks/usePreviewMessages';
usePreviewMessages();
</script>
<main>
<slot />
</main>
<style>
main {
min-height: 100vh;
}
</style>
4. Page Component with Live Preview
<!-- src/routes/blog/[slug]/+page.svelte -->
<script lang="ts">
import { page } from '$app/stores';
import { previewStore, currentPageContent, mergeContent } from '$lib/stores/preview';
import type { PageContent } from '$lib/stores/preview';
export let data: { post: PageContent };
let displayContent: PageContent;
// Subscribe to preview changes
const unsubscribe = previewStore.subscribe(preview => {
if (preview.isPreviewMode && Object.keys(preview.overrides).length > 0) {
displayContent = mergeContent(data.post, preview.overrides);
} else {
displayContent = data.post;
}
});
onDestroy(unsubscribe);
import { onDestroy } from 'svelte';
</script>
<article class:preview-mode={$previewStore.isPreviewMode}>
{#if $previewStore.isPreviewMode}
<div class="preview-banner">
<span class="badge">PREVIEW MODE</span>
<span class="dirty-indicator" title={$previewStore.isDirty ? 'Unsaved changes' : ''}>
{$previewStore.isDirty ? '●' : '○'}
</span>
</div>
{/if}
<header>
<h1 contenteditable="false">{displayContent.title}</h1>
{#if displayContent.seo}
<div class="meta">
<p class="description">{displayContent.seo.metaDescription}</p>
</div>
{/if}
</header>
<main>
{@html displayContent.content}
</main>
{#if displayContent.metadata}
<footer class="metadata">
{#if displayContent.metadata.author}
<span>By {displayContent.metadata.author}</span>
{/if}
{#if displayContent.metadata.publishedAt}
<time datetime={displayContent.metadata.publishedAt}>
{new Date(displayContent.metadata.publishedAt).toLocaleDateString()}
</time>
{/if}
</footer>
{/if}
</article>
<style>
article {
max-width: 800px;
margin: 0 auto;
padding: 2rem;
}
article.preview-mode {
background-color: #fffbea;
border: 2px dashed #ffc107;
}
.preview-banner {
display: flex;
align-items: center;
gap: 0.5rem;
margin-bottom: 1rem;
padding: 0.5rem 1rem;
background-color: #fff3cd;
border-radius: 4px;
font-size: 0.875rem;
}
.badge {
font-weight: 600;
color: #ff6200;
}
.dirty-indicator {
font-size: 1.5rem;
color: #ff6200;
animation: pulse 1s infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
h1 {
margin: 0;
font-size: 2rem;
}
.description {
color: #666;
margin: 0.5rem 0 0;
}
.metadata {
display: flex;
gap: 1rem;
margin-top: 2rem;
padding-top: 1rem;
border-top: 1px solid #eee;
color: #666;
font-size: 0.875rem;
}
</style>
5. CMS Interface Component
// cms/src/components/PreviewFrame.svelte
<script lang="ts">
import { onMount } from 'svelte';
import type { PageContent } from '$lib/types';
export let content: PageContent;
export let previewUrl: string = 'http://localhost:5173';
let iframeElement: HTMLIFrameElement;
let isConnected = false;
let messageLog: Array<{ timestamp: Date; message: string; type: 'sent' | 'received' }> = [];
let updateQueue: Partial<PageContent> = {};
let debounceTimer: ReturnType<typeof setTimeout>;
const DEBOUNCE_DELAY = 500;
// Log messages for debugging
function logMessage(message: string, type: 'sent' | 'received') {
messageLog = [
{ timestamp: new Date(), message, type },
...messageLog.slice(0, 49)
];
}
// Send message to iframe with error handling
function postMessage(data: unknown) {
if (!iframeElement?.contentWindow) {
console.error('Cannot post message: iframe not ready');
return;
}
try {
iframeElement.contentWindow.postMessage(data, previewUrl);
logMessage(JSON.stringify(data), 'sent');
} catch (error) {
console.error('Error posting message:', error);
}
}
// Debounced update
function debouncedUpdate() {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
if (Object.keys(updateQueue).length > 0) {
postMessage({
type: 'PREVIEW_UPDATE',
payload: updateQueue
});
updateQueue = {};
}
}, DEBOUNCE_DELAY);
}
// Queue an update (batches multiple updates)
export function updatePreview(updates: Partial<PageContent>) {
updateQueue = { ...updateQueue, ...updates };
debouncedUpdate();
}
// Initialize preview
function initializePreview() {
postMessage({
type: 'PREVIEW_INIT',
payload: content
});
}
// Check connection
function checkConnection() {
postMessage({ type: 'PING' });
setTimeout(() => {
if (!isConnected) {
console.warn('Preview frame did not respond to PING');
}
}, 1000);
}
// Handle messages from preview frame
function handleMessage(event: MessageEvent) {
// Security check
if (!event.origin.startsWith('http://localhost')) {
console.warn('Received message from untrusted origin:', event.origin);
return;
}
const { data } = event;
logMessage(JSON.stringify(data), 'received');
switch (data.type) {
case 'PREVIEW_READY':
isConnected = true;
console.log('Preview frame ready');
initializePreview();
break;
case 'PONG':
isConnected = true;
console.log('Preview frame responded to ping');
break;
case 'ACK':
console.log('Preview frame acknowledged:', data.data?.message);
break;
case 'ERROR':
console.error('Preview frame error:', data.data?.message);
break;
}
}
onMount(() => {
window.addEventListener('message', handleMessage);
// Wait for iframe to load
if (iframeElement) {
iframeElement.onload = () => {
console.log('Preview frame loaded, checking connection...');
setTimeout(checkConnection, 500);
};
}
return () => {
window.removeEventListener('message', handleMessage);
clearTimeout(debounceTimer);
};
});
function clearPreview() {
postMessage({ type: 'PREVIEW_CLEAR' });
}
</script>
<div class="preview-container">
<div class="preview-panel">
<div class="preview-header">
<h2>Live Preview</h2>
<div class="header-actions">
<button
class="connection-indicator"
class:connected={isConnected}
title={isConnected ? 'Connected' : 'Disconnected'}
>
● {isConnected ? 'Live' : 'Offline'}
</button>
<button on:click={checkConnection} title="Test connection">
🔄 Test
</button>
<button on:click={clearPreview} title="Clear preview">
✕ Clear
</button>
</div>
</div>
<div class="iframe-wrapper">
<iframe
bind:this={iframeElement}
src={previewUrl}
title="Live Preview"
sandbox="allow-same-origin allow-scripts allow-forms"
/>
</div>
<div class="message-log">
<h3>Debug Log</h3>
<div class="log-entries">
{#each messageLog as entry (entry.timestamp.getTime())}
<div class="log-entry {entry.type}">
<time>{entry.timestamp.toLocaleTimeString()}</time>
<span class="type">[{entry.type.toUpperCase()}]</span>
<span class="message">{entry.message}</span>
</div>
{/each}
</div>
</div>
</div>
<div class="editor-panel">
<slot />
</div>
</div>
<style>
.preview-container {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
height: 100vh;
}
.preview-panel {
display: flex;
flex-direction: column;
background: white;
border-right: 1px solid #ddd;
overflow: hidden;
}
.preview-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
border-bottom: 1px solid #ddd;
}
.header-actions {
display: flex;
gap: 0.5rem;
}
button {
padding: 0.5rem 1rem;
border: 1px solid #ddd;
border-radius: 4px;
background: white;
cursor: pointer;
font-size: 0.875rem;
transition: all 0.2s;
}
button:hover {
background: #f5f5f5;
}
.connection-indicator {
color: #999;
}
.connection-indicator.connected {
color: #28a745;
border-color: #28a745;
}
.iframe-wrapper {
flex: 1;
overflow: hidden;
background: #f9f9f9;
}
iframe {
width: 100%;
height: 100%;
border: none;
}
.message-log {
flex: 0 0 200px;
border-top: 1px solid #ddd;
overflow: hidden;
background: #f5f5f5;
font-size: 0.75rem;
}
.message-log h3 {
margin: 0.5rem;
font-size: 0.875rem;
}
.log-entries {
height: 190px;
overflow-y: auto;
font-family: monospace;
}
.log-entry {
padding: 0.25rem 0.5rem;
border-bottom: 1px solid #ddd;
display: flex;
gap: 0.5rem;
align-items: flex-start;
}
.log-entry.sent {
background: #e8f5e9;
}
.log-entry.received {
background: #e3f2fd;
}
time {
flex: 0 0 auto;
color: #999;
}
.type {
flex: 0 0 auto;
font-weight: bold;
color: #333;
}
.message {
flex: 1;
word-break: break-all;
color: #666;
}
.editor-panel {
padding: 1rem;
overflow-y: auto;
}
</style>
6. CMS Page Example
<!-- cms/src/routes/editor/+page.svelte -->
<script lang="ts">
import { onMount } from 'svelte';
import PreviewFrame from '../components/PreviewFrame.svelte';
import ContentEditor from '../components/ContentEditor.svelte';
import type { PageContent } from '$lib/types';
let previewFrame: PreviewFrame;
let currentContent: PageContent = {
id: '1',
title: 'Sample Post',
slug: 'sample-post',
content: '<p>This is a sample post content.</p>',
seo: {
metaDescription: 'A sample post for testing',
keywords: ['sample', 'test']
},
metadata: {
author: 'John Doe',
publishedAt: new Date().toISOString()
}
};
function handleContentChange(event: CustomEvent<Partial<PageContent>>) {
currentContent = { ...currentContent, ...event.detail };
previewFrame?.updatePreview(event.detail);
}
onMount(() => {
// Simulate loading content from API
console.log('Editor page mounted');
});
</script>
<PreviewFrame bind:this={previewFrame} content={currentContent}>
<ContentEditor bind:content={currentContent} on:change={handleContentChange} />
</PreviewFrame>
<style>
:global(body) {
margin: 0;
padding: 0;
}
</style>
7. Content Editor Component
<!-- cms/src/components/ContentEditor.svelte -->
<script lang="ts">
import { createEventDispatcher } from 'svelte';
import type { PageContent } from '$lib/types';
export let content: PageContent;
const dispatch = createEventDispatcher<Partial<PageContent>>();
function handleTitleChange(e: Event) {
const title = (e.target as HTMLInputElement).value;
dispatch('change', { title });
}
function handleSlugChange(e: Event) {
const slug = (e.target as HTMLInputElement).value;
dispatch('change', { slug });
}
function handleContentChange(e: Event) {
const contentText = (e.target as HTMLTextAreaElement).value;
dispatch('change', { content: contentText });
}
function handleMetaDescriptionChange(e: Event) {
const metaDescription = (e.target as HTMLInputElement).value;
dispatch('change', {
seo: { ...content.seo, metaDescription }
});
}
function handleAuthorChange(e: Event) {
const author = (e.target as HTMLInputElement).value;
dispatch('change', {
metadata: { ...content.metadata, author }
});
}
</script>
<div class="editor">
<form on:submit|preventDefault>
<div class="form-group">
<label for="title">Title</label>
<input
id="title"
type="text"
value={content.title}
on:input={handleTitleChange}
placeholder="Page title"
/>
</div>
<div class="form-group">
<label for="slug">Slug</label>
<input
id="slug"
type="text"
value={content.slug}
on:input={handleSlugChange}
placeholder="page-slug"
/>
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea
id="content"
value={content.content}
on:input={handleContentChange}
placeholder="Page content (HTML)"
rows="10"
/>
</div>
<div class="form-section">
<h3>SEO</h3>
<div class="form-group">
<label for="meta-description">Meta Description</label>
<input
id="meta-description"
type="text"
value={content.seo?.metaDescription || ''}
on:input={handleMetaDescriptionChange}
placeholder="Meta description (max 160 chars)"
maxlength="160"
/>
<small>
{content.seo?.metaDescription?.length || 0}/160
</small>
</div>
</div>
<div class="form-section">
<h3>Metadata</h3>
<div class="form-group">
<label for="author">Author</label>
<input
id="author"
type="text"
value={content.metadata?.author || ''}
on:input={handleAuthorChange}
placeholder="Author name"
/>
</div>
</div>
<div class="form-actions">
<button type="button" class="btn-primary">Save Draft</button>
<button type="button" class="btn-secondary">Publish</button>
</div>
</form>
</div>
<style>
.editor {
max-width: 600px;
}
form {
display: flex;
flex-direction: column;
gap: 1rem;
}
.form-group {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.form-section {
padding: 1rem;
background: #f9f9f9;
border-radius: 4px;
border-left: 3px solid #007bff;
}
.form-section h3 {
margin: 0 0 1rem 0;
font-size: 1rem;
}
label {
font-weight: 600;
color: #333;
}
input,
textarea {
padding: 0.75rem;
border: 1px solid #ddd;
border-radius: 4px;
font: inherit;
font-size: 0.875rem;
}
input:focus,
textarea:focus {
outline: none;
border-color: #007bff;
box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
}
textarea {
resize: vertical;
font-family: monospace;
}
small {
color: #666;
font-size: 0.75rem;
}
.form-actions {
display: flex;
gap: 1rem;
margin-top: 1rem;
}
button {
padding: 0.75rem 1.5rem;
border: none;
border-radius: 4px;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
}
.btn-primary {
background: #007bff;
color: white;
}
.btn-primary:hover {
background: #0056b3;
}
.btn-secondary {
background: white;
color: #007bff;
border: 2px solid #007bff;
}
.btn-secondary:hover {
background: #f0f7ff;
}
</style>
8. Environment Configuration
# .env.development
VITE_CMS_ORIGINS=http://localhost:3000,http://localhost:5173
# cms/.env.development
VITE_PREVIEW_URL=http://localhost:5173
9. Types Definition
// src/lib/types/cms.ts
export interface PageContent {
id: string;
title: string;
slug: string;
content: string;
metadata?: Record<string, unknown>;
seo?: {
metaDescription: string;
keywords: string[];
};
}
export interface PreviewMessage {
type: 'PREVIEW_INIT' | 'PREVIEW_UPDATE' | 'PREVIEW_CLEAR' | 'PING';
payload?: Partial<PageContent>;
}
export interface PreviewResponse {
type: 'PREVIEW_READY' | 'ACK' | 'ERROR' | 'PONG';
status: 'success' | 'error';
data?: Record<string, unknown>;
}
10. Security Middleware
// src/lib/middleware/previewSecurity.ts
export interface SecurityConfig {
allowedOrigins: string[];
enableContentSanitization: boolean;
maxPayloadSize: number;
rateLimitPerSecond: number;
}
export class PreviewSecurityManager {
private config: SecurityConfig;
private requestLog: Map<string, number[]> = new Map();
constructor(config: Partial<SecurityConfig> = {}) {
this.config = {
allowedOrigins: config.allowedOrigins || [
'http://localhost:3000',
'http://localhost:5173'
],
enableContentSanitization: config.enableContentSanitization !== false,
maxPayloadSize: config.maxPayloadSize || 1024 * 1024, // 1MB
rateLimitPerSecond: config.rateLimitPerSecond || 10
};
}
validateOrigin(origin: string): boolean {
return this.config.allowedOrigins.some(allowed => {
// Support wildcards in development
if (allowed.includes('*')) {
const regex = new RegExp('^' + allowed.replace(/\*/g, '.*') + '$');
return regex.test(origin);
}
return allowed === origin;
});
}
checkRateLimit(origin: string): boolean {
const now = Date.now();
const requests = this.requestLog.get(origin) || [];
// Remove old requests
const recentRequests = requests.filter(time => now - time < 1000);
if (recentRequests.length >= this.config.rateLimitPerSecond) {
return false;
}
recentRequests.push(now);
this.requestLog.set(origin, recentRequests);
return true;
}
validatePayloadSize(payload: unknown): boolean {
const size = JSON.stringify(payload).length;
return size <= this.config.maxPayloadSize;
}
sanitizeHtml(html: string): string {
// Use a library like DOMPurify in production
// This is a basic example
const div = document.createElement('div');
div.textContent = html;
return div.innerHTML;
}
}
Key Features
✅ Real-time Preview - Instant updates without page reload
✅ Message Batching - Debounced updates to prevent flooding
✅ Security - Origin validation, rate limiting, payload size checks
✅ Error Handling - Comprehensive error messages and logging
✅ Type Safety - Full TypeScript support
✅ Sandbox Isolation - Iframe sandbox attributes for security
✅ Debug Logging - Visual message log for development
✅ Connection Status - Real-time connection indicator
This implementation provides a production-ready live preview system for headless CMS integration!