The user wants a CMS (Content Management System) implemented using SvelteKit.
Key requirements:
SvelteKit: The framework to use.
Real-time content editing: Changes should reflect immediately or near-immediately.
Preview: Users need to see how the content looks before publishing or as they type.
Architectural Decisions:
Data Storage: Since this is a "real-time" demo or a lightweight implementation, a full-blown SQL database might be overkill for the code snippet, but I should structure it so it could connect to one. For the sake of a self-contained example, using a simple in-memory store or a JSON file (using the fs module) is best. I'll use a JSON file for persistence across restarts but keep it simple.
Real-time Aspect: How to achieve real-time?
Option A: WebSockets. SvelteKit supports this, but it adds complexity.
Option B: Server-Sent Events (SSE). Good for one-way updates.
Option C: Polling. Simple but inefficient.
Option D: Optimistic UI / Local State + Debounced Save. This is often what people mean by "real-time editing" in a CMS (like Notion or Ghost). You type, it updates the preview immediately, and saves in the background.
Refinement: To make it truly "real-time" (collaborative or live preview in a separate window), WebSockets are best. However, for a single user editing and seeing a preview side-by-side, standard Svelte reactivity is sufficient.
Decision: I will implement a "Side-by-Side" editor using Svelte's two-way binding (or unidirectional data flow) where typing updates the preview pane instantly via local state, and saves to the "server" (API route) periodically or on blur.
Project Structure:
src/routes: SvelteKit file structure.
src/lib/stores: Svelte stores for state management.
src/lib/server/db.ts: Mock database logic.
Key Features to Implement:
Page List: To select a page to edit.
Editor: A text area (or contenteditable div) for Markdown or HTML. Let's stick to Markdown for simplicity and safety, using a parser for the preview.
Preview Pane: Renders the parsed Markdown.
API Endpoints: GET and POST for page content.
Drafting the Solution Steps:
Setup & Dependencies: marked for Markdown parsing.
Database (Mock): A simple module to read/write a JSON file.
API Routes:
GET /api/pages/[id]: Fetch content.
POST /api/pages/[id]: Save content.
Frontend (The Editor Route):
Split screen (CSS Grid/Flex).
Left: Textarea bound to a variable.
Right: HTML rendered from that variable.
Auto-save logic (debounce).
Refining the "Real-time" Requirement:
If the user meant "Live Preview" (WYSIWYG), standard reactivity works.
If the user meant "Collaborative" (Google Docs style), that requires CRDTs or WebSockets.
Assumption: Most users asking for a CMS tutorial want a split-screen "Notion-like" or "Ghost-like" experience where the preview updates instantly as you type. I will focus on Live Preview.
src/routes/api/pages/[id]/+server.ts (The Backend)
src/routes/preview/[id]/+page.svelte (The Public View)
Logic:
Use marked to convert Markdown to HTML.
Use svelte-debounce or a simple setTimeout for auto-saving.
Code Construction:
Database: Keep it simple. pages.json.
API: Standard SvelteKit json helpers.
Editor:
Load data in load function.
Bind textarea to content.
$: renderedHtml = marked(content)
Save function.
Let's write the code.
Self-Correction during drafting: Dealing with file system in Server-Side Rendering (SSR) needs care. Ensure fs calls are only in +server.ts or load functions running on the server.
Bonus: To make it feel like a "Real-time CMS", I will add a status indicator (Saving... / Saved).
Detailed Code Components:
package.json: Needs marked.
database.ts: A class to manage pages.
routes/+page.svelte: List of pages.
routes/edit/[slug]/+page.svelte: The core logic.
Script: imports, props (data from load).
State: content, title.
Reactivity: html = parse(content).
Actions: save().
Final Polish: Add some CSS to make it look decent (Tailwind classes or standard CSS). I'll use standard CSS for fewer dependencies, or just generic classes assuming the user handles styling, but plain CSS is safer for a copy-paste solution.
Let's structure the response:
Prerequisites.
Directory structure overview.
Step-by-step code blocks.
Explanation of how the "Real-time" preview works.
Special consideration: The prompt asks for a "SvelteKit-based CMS". I should provide a minimal but functional version.
Mock DB: map<slug, {title, content}>.
Markdown: Use marked library.
Let's refine the Editor UI.
Two columns: Textarea (Source) | Div (Preview).
Resize handling? Just use CSS Grid 1fr 1fr.
Okay, ready to generate. I will present a complete, runnable example structure.
src/lib/server/db.ts: The persistence layer.
src/routes/api/pages/[slug]/+server.ts: The CRUD API.
src/routes/admin/+page.svelte: The dashboard.
src/routes/admin/edit/[slug]/+page.svelte: The live editor.
src/routes/[slug]/+page.svelte: The public preview (uses the same layout but renders the result).
Wait, the prompt asks for "Real-time content editing and preview". Usually, this means side-by-side. I will put the side-by-side in the edit route.
Let's go.
This is a complete, implementable example of a "Headless" CMS built with SvelteKit. It features a side-by-side interface where you edit Markdown on the left and see a fully rendered, real-time preview on the right.
Key Features
Real-time Preview: Utilizes Svelte's reactive declarations ($:) to update the preview instantly as you type.
Persistence: Uses the local file system (JSON) to store content so it survives refreshes.
Markdown Support: Uses marked.js to parse Markdown.
Auto-saving: Debounced saving to the backend to prevent overloading the server.
1. Project Setup
First, create a new SvelteKit project and install the necessary dependencies.
Reactive Chain: In the admin panel (+page.svelte), the variable body is bound to the <textarea>. Every time you type a character, Svelte's $: syntax detects the change.
Markdown Parsing: The change triggers marked.parse(body), updating renderedHtml instantly.
DOM Update: Svelte efficiently patches the DOM in the .preview-pane div, giving you a WYSIWYG-style experience without the complexity of a content-editable div.
Debounced Save: The $: watcher also clears a timer and starts a new one. If you stop typing for 800ms, the save() function fires, sending the JSON to your API route, which writes to disk.
Usage
Run the dev server: npm run dev.
Create Content: Navigate to http://localhost:5173/admin/home (the code sets up a default "home" page).
Edit: Type in the left pane. You will see the rendered HTML appear immediately on the right.
View: Navigate to http://localhost:5173/home to see the public view.
Persistence: Refresh the admin page; your content remains because it was saved to content.json.
<script context="module">
// Load the initial content from the server
export async function load({ params, fetch }) {
// In a real app, you might fetch this from an API
// Here we simulate fetching the specific page data
const { getContent } = await import('$lib/server/db');
const allContent = getContent();
const pageData = allContent[params.slug] || { title: 'New Page', body: '' };
return {
props: {
initialTitle: pageData.title,
initialBody: pageData.body,
slug: params.slug
}
};
}
</script>
<script>
import { marked } from 'marked';
import { browser } from '$app/environment';
// Props from the load function
export let initialTitle;
export let initialBody;
export let slug;
// Local state
let title = initialTitle;
let body = initialBody;
let status = 'Saved'; // Status indicator
let timeout;
// 1. REAL-TIME PREVIEW REACTIVITY
// This runs whenever 'body' or 'title' changes
$: renderedHtml = marked.parse(body || '');
$: fullPreviewHtml = `<h1>${title}</h1>` + renderedHtml;
// 2. AUTO-SAVE LOGIC
// We use a debounce function to save only after typing stops for 800ms
async function save() {
status = 'Saving...';
const res = await fetch(`/api/save/${slug}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title, body })
});
if (res.ok) status = 'Saved';
else status = 'Error';
}
// Watch for changes and trigger save
$: if (browser && (title !== initialTitle || body !== initialBody)) {
clearTimeout(timeout);
status = 'Unsaved changes...';
timeout = setTimeout(save, 800);
}
</script>
<div class="cms-container">
<header>
<h2>Editing: {slug}</h2>
<span class="status">{status}</span>
</header>
<div class="editor-grid">
<!-- Input Pane -->
<div class="pane input-pane">
<input type="text" bind:value={title} placeholder="Page Title" />
<textarea bind:value={body} placeholder="Markdown content here..."></textarea>
</div>
<!-- Preview Pane -->
<div class="pane preview-pane">
{@html fullPreviewHtml}
</div>
</div>
</div>
<style>
.cms-container {
display: flex;
flex-direction: column;
height: 100vh;
font-family: sans-serif;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
background: #f4f4f4;
border-bottom: 1px solid #ddd;
}
.status {
font-size: 0.8rem;
color: #666;
}
.editor-grid {
display: grid;
grid-template-columns: 1fr 1fr;
flex: 1;
overflow: hidden;
}
.pane {
padding: 1rem;
overflow-y: auto;
height: 100%;
box-sizing: border-box;
}
/* Editor Styling */
.input-pane input {
width: 100%;
font-size: 1.5rem;
font-weight: bold;
margin-bottom: 1rem;
border: none;
border-bottom: 2px solid #eee;
outline: none;
}
.input-pane textarea {
width: 100%;
height: calc(100% - 60px);
resize: none;
border: 1px solid #eee;
padding: 1rem;
font-family: monospace;
font-size: 1rem;
outline: none;
}
/* Preview Styling */
.preview-pane {
background: white;
border-left: 1px solid #ddd;
}
</style>