Developing the SvelteKit CMS
I'm now focusing on the essential core features of the SvelteKit CMS. I've successfully identified the need for user authentication, content creation and editing capabilities. The goal is now to establish a scalable architecture for handling content types, with the intent of keeping the CMS easy to customize. Next, I'll dive into data modelling to determine how content will be stored.
Prioritizing Real-time Editing
I'm now prioritizing the implementation of real-time content editing and preview functionality within the SvelteKit CMS. Integrating Supabase as the backend is proving valuable, particularly with its out-of-the-box PostgreSQL database and Realtime capabilities. The next step is to design the editing interface and establish a real-time data syncing mechanism, likely using Svelte stores, to ensure instant updates.
Defining Real-time Logic
I'm now focusing on the real-time interaction between Supabase and Svelte stores. I'm carefully evaluating different approaches, particularly updating the database on every keystroke versus managing a local state. The plan involves setting up a SvelteKit project, defining database schema, and creating helper scripts for the Supabase client. My current thoughts are centered on implementing a split-pane admin interface with live previews and leveraging Svelte stores along with the Supabase on channel for immediate updates.
Clarifying Realtime Workflow
I'm now clarifying the ideal workflow for the SvelteKit CMS. The goal is to provide a smooth, Google Docs-like collaborative experience. The proposed flow is now: Edit Trigger -> Debounced Database Update -> Realtime Push -> UI Update. I'm leaning toward a split-screen design: an editor pane writes to the database, and the preview pane listens for database changes via Supabase Realtime, avoiding the complexity of broadcast events. Next, I'll start constructing the code structure.
Designing Real-time Architecture
I'm now focusing on designing the real-time interaction between the Supabase database and the Svelte frontend. The objective is to achieve a responsive, user-friendly CMS experience. The function updatePost will call Supabase's update method, and debounce will be utilized to minimize database calls during user input. For the public view at src/routes/post/[id]/+page.svelte, I'll implement a Supabase channel to listen for UPDATE events on a specific post ID and update the local store accordingly. To enhance the CMS feel, a dedicated "Editor" route with a side-by-side editing and previewing layout will be created, with a specific file structure, including lib/db.js, routes/editor/[id]/+page.server.ts, and routes/editor/[id]/+page.svelte. In terms of the frontend, I plan to use Svelte 4/5 standard reactivity (specifically, export let data for the current SvelteKit project).
Building the Tutorial
I'm now putting together the steps for the tutorial. It will cover essential setup like Node and Supabase, database configuration with provided SQL, environment variables, the Supabase client library code, and the central editor page where debouncing will be implemented to give a real-time feel. The tutorial will conclude with a live preview component. I'm focusing on ensuring it clearly explains how to make the typing experience feel instant.
Adding Collaboration
I'm now focusing on implementing real-time collaboration. The core idea is to sync edits across multiple sessions using Supabase Realtime. I'll utilize a split-view layout with a Markdown editor on the left and a live preview on the right. Currently, I'm integrating Supabase's Realtime capabilities to ensure instant updates between different browser windows or tabs. The next step involves incorporating the editor and live preview components.
This is a complete implementation of a real-time CMS using SvelteKit, Supabase (for the database and real-time subscriptions), and Marked (for Markdown rendering).
This implementation allows you to type in an editor on the left and see changes update instantly on the right (and on any other connected client).
Prerequisites
- A free Supabase project.
- Node.js installed.
Step 1: Database Setup (Supabase)
Go to your Supabase project's SQL Editor and run this query to set up the table and enable Realtime.
-- Create the posts table
create table posts (
id uuid default gen_random_uuid() primary key,
title text,
content text,
slug text unique,
updated_at timestamp with time zone default timezone('utc'::text, now())
);
-- Insert a dummy post
insert into posts (title, content, slug)
values ('Hello World', '# Welcome to your CMS\n\nStart editing to see magic happen.', 'hello-world');
-- IMPORTANT: Turn on Realtime for this table
alter publication supabase_realtime add table posts;
Get your Project URL and Anon Key from Project Settings -> API.
Step 2: Scaffold Project
Create the project and install dependencies:
npm create svelte@latest my-cms
# Select "Skeleton project", "TypeScript", etc.
cd my-cms
npm install
npm install @supabase/supabase-js marked lodash
npm install -D autoprefixer postcss tailwindcss
npx tailwindcss init -p
Note: We install lodash for debouncing the database saves.
Configure Tailwind in tailwind.config.js:
/** @type {import('tailwindcss').Config} */
export default {
content: ['./src/**/*.{html,js,svelte,ts}'],
theme: {
extend: {},
},
plugins: [],
}
Add Tailwind directives to src/app.css:
@tailwind base;
@tailwind components;
@tailwind utilities;
Step 3: Connect Supabase
Create a .env file in the root:
PUBLIC_SUPABASE_URL=your_project_url_here
PUBLIC_SUPABASE_ANON_KEY=your_anon_key_here
Create the client helper at src/lib/supabase.ts:
import { createClient } from '@supabase/supabase-js';
import { PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY } from '$env/static/public';
export const supabase = createClient(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY);
Step 4: Create the Server Load Function
We need to fetch the initial data from the server. Create src/routes/editor/[slug]/+page.server.ts:
import { supabase } from '$lib/supabase';
import { error } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ params }) => {
const { data, error: dbError } = await supabase
.from('posts')
.select('*')
.eq('slug', params.slug)
.single();
if (dbError || !data) {
throw error(404, 'Post not found');
}
return {
post: data
};
};
Step 5: The Real-time CMS Interface
This is the core logic. We will implement:
- Local State: For instant UI updates while typing.
- Debounced Save: Updates the DB after you stop typing (to avoid API limits).
- Real-time Listener: Updates the UI if someone else edits the post.
Create src/routes/editor/[slug]/+page.svelte:
<script lang="ts">
import { onMount, onDestroy } from 'svelte';
import { supabase } from '$lib/supabase';
import { marked } from 'marked';
import debounce from 'lodash/debounce';
import type { PageData } from './$types';
export let data: PageData;
// Local state initialized with server data
let post = { ...data.post };
let isSaving = false;
// Separate variable for the rendered HTML to avoid recalculating unnecessarily
$: parsedContent = marked.parse(post.content || '');
// 1. Handle Database Updates (Debounced)
// We wait 500ms after typing stops before sending to DB
const saveToDb = debounce(async (updatedPost) => {
isSaving = true;
const { error } = await supabase
.from('posts')
.update({
title: updatedPost.title,
content: updatedPost.content,
updated_at: new Date()
})
.eq('id', updatedPost.id);
if (error) console.error('Error saving:', error);
isSaving = false;
}, 500);
// Reactive statement: Whenever post changes, trigger save
// We maintain a reference to avoid infinite loops from incoming realtime events
let lastServerContent = data.post.content;
function handleInput() {
// Only save if content is different from what we last got from server
if (post.content !== lastServerContent) {
saveToDb(post);
}
}
// 2. Handle Real-time Subscriptions
let channel: any;
onMount(() => {
channel = supabase
.channel(`post-${post.id}`)
.on(
'postgres_changes',
{
event: 'UPDATE',
schema: 'public',
table: 'posts',
filter: `id=eq.${post.id}`
},
(payload) => {
// Start of "Remote Cursor" logic
// Only update local state if the change didn't come from us
// (simple check: is the incoming content different from our local state?)
if (payload.new.content !== post.content) {
post = { ...post, ...payload.new };
lastServerContent = payload.new.content; // Sync reference
}
}
)
.subscribe();
});
onDestroy(() => {
if (channel) supabase.removeChannel(channel);
});
</script>
<div class="flex h-screen flex-col bg-gray-900 text-white">
<!-- Header -->
<header class="flex items-center justify-between border-b border-gray-800 bg-gray-950 px-6 py-4">
<div class="flex items-center gap-4">
<h1 class="text-xl font-bold text-gray-100">SvelteKit Realtime CMS</h1>
<span class="rounded-full bg-gray-800 px-3 py-1 text-xs text-gray-400">
{isSaving ? 'Saving...' : 'Synced'}
</span>
</div>
<div class="text-sm text-gray-500">Editing: <span class="text-white">{post.slug}</span></div>
</header>
<!-- Main Content -->
<main class="flex flex-1 overflow-hidden">
<!-- Left: Editor -->
<section class="flex-1 border-r border-gray-800 bg-gray-900 p-6">
<input
type="text"
bind:value={post.title}
on:input={handleInput}
class="mb-4 w-full bg-transparent text-3xl font-bold text-white outline-none placeholder:text-gray-700"
placeholder="Post Title..."
/>
<textarea
bind:value={post.content}
on:input={handleInput}
class="h-full w-full resize-none bg-transparent font-mono text-sm leading-relaxed text-gray-300 outline-none placeholder:text-gray-700"
placeholder="Write your markdown here..."
></textarea>
</section>
<!-- Right: Live Preview -->
<section class="flex-1 overflow-y-auto bg-white p-8 text-gray-900">
<h1 class="mb-6 text-4xl font-extrabold">{post.title}</h1>
<article class="prose prose-lg max-w-none">
{@html parsedContent}
</article>
</section>
</main>
</div>
<style>
/* Add simple prose styling for markdown elements */
:global(.prose h1) { font-size: 2em; font-weight: 800; margin-bottom: 0.5em; }
:global(.prose h2) { font-size: 1.5em; font-weight: 700; margin-top: 1em; margin-bottom: 0.5em; }
:global(.prose p) { margin-bottom: 1em; line-height: 1.6; }
:global(.prose ul) { list-style-type: disc; padding-left: 1.5em; margin-bottom: 1em; }
:global(.prose code) { background: #f3f4f6; padding: 0.2em 0.4em; border-radius: 0.25em; font-family: monospace; }
</style>
Step 6: Run it
- Start the server:
npm run dev
- Open your browser to:
http://localhost:5173/editor/hello-world.
Verification: Real-time Test
- Open the same URL in a second browser window (or Incognito mode).
- Type in the Left pane of Window A.
- Observe:
- Reflects Locally: Instant preview on Window A Right pane.
- Reflects Remotely: After 500ms (debounce), Window B updates automatically via Supabase Realtime.
Key Concepts Used
- SvelteKit Server Load: Fetches data server-side first for SEO and initial paint speed.
- Debouncing: Prevents making a database request on every single keystroke, which saves API quota and reduces network traffic.
- Supabase Realtime: The
channel.on('postgres_changes'...) listener allows the client to react to changes made by other users.
- Optimistic UI: The UI updates immediately via Svelte's local state
bind:value, while the database sync happens in the background.