Skip to content

Use Visual Editor with SvelteKit

Learn how to use Visual Editor with a SvelteKit-based website.

Configure Visual Editor for a SvelteKit project

Section titled “Configure Visual Editor for a SvelteKit project”

SvelteKit is supported through the ssgName: custom option (learn more.

Follow the example repository for a concrete example of integrating Visual Editor with a SvelteKit. Here’s an excerpt from Visual Editor configuration file:

// stackbit.config.js
export default {
stackbitVersion: "~0.6.0",
cmsName: "contentful",
nodeVersion: "16",
ssgName: "custom",
devCommand: "./node_modules/.bin/vite --port {PORT}",
experimental: {
ssg: {
name: "sveltekit",
logPatterns: { up: [" ready in "] },
passthrough: ["/vite-hmr/**"]
}
}
};

Note the use of some experimental configuration properties to ensure compatibility with Vite (the development server used by SvelteKit and others):

  1. experimental.ssg.logPatterns.up is set to [' ready in ']. This is part of the log message that appears when the Vite dev server is ready to accept requests.
  2. experimental.ssg.passthrough is set to a dedicated relative path to Vite’s HMR Websocket endpoint. The path ‘/vite-hmr/’ is configured accordingly in vite.config.js (see here. With this setting, any code changes will trigger a client refresh through Vite’s HMR mechanism, without interference from our container.

In the example repository, content changes are handled by:

  • Capturing the 'stackbitObjectsChanged' window event.
  • Then, invalidating the JSON endpoint providing data to the current page, which will cause the current page to refresh.

This behavior is found at the root __layout.svelte file, which enables it across the website without needing to further modify any other module.

Here are the contents of this file (source:

<script context="module">
export async function load({ url }) {
return {
props: {
currentUrl: url.pathname,
},
};
}
</script>
<script>
import { invalidate } from "$app/navigation";
export let currentUrl;
function onContentChange(event) {
invalidate(`${currentUrl}.json`);
console.log("Content update - invalidating current page");
}
</script>
<svelte:window
on:stackbitObjectsChanged|preventDefault={onContentChange}/>
<slot />

SvelteKit + Contentful Example.

Originally adopted from this demo on GitHub, with added Visual Editor support and modifications for compatibility with the latest version of SvelteKit.