# SvelteKit quickstart

> A SvelteKit website with Svelte 5 that renders every CMS Orbit page at its own address from a server load function, previews drafts in the editor and refreshes when editors publish.

Source: https://docs.bifrostorbit.com/cms/developers/quickstart-sveltekit/

In about 20 minutes you build a SvelteKit website for Northwilds that reads its pages from CMS Orbit. Every page an editor publishes appears at its own address, each component is drawn by a Svelte component of yours, editors see their drafts in the live preview, and publishing refreshes the page straight away.

The SDK's client, `@bifrost-orbit-cms/sdk`, runs on the server in load functions and `+server.ts` endpoints. Its React and Next.js helpers are not used: you write the Svelte side yourself, which takes a handful of small files.

**Tested with:** SvelteKit 3.1, Svelte 5.57, Vite 8.3, `@sveltejs/adapter-node` 6.0, `@bifrost-orbit-cms/sdk` 0.12.0, TypeScript 6.0, Node.js 24.

Prefer to start from a working project? Use the starter: [bifrost-orbit/cms-starter-sveltekit](https://github.com/bifrost-orbit/cms-starter-sveltekit), the finished code of this guide.

## Before you start

You need:

- **A CMS Orbit space** with at least one published page, such as the home page at `/`.
- **Two API keys** from **Configuration › API keys**: a public `cms_pk_` key for the live website and a secret `cms_sk_` key with **Read drafts** on, for previews. Step 4 of [Connect a website to CMS Orbit](https://docs.bifrostorbit.com/cms/developers/connect-a-website/) shows how to create them.
- **The API address**, `https://api.bifrostorbit.com/cms`, and **the region key**, such as `global` or `germany`, from **Configuration › Environments**.
- **Node.js 20 or later.**

## 1. Create the project

```bash
npx sv@latest create northwilds-site --template minimal --types ts --add sveltekit-adapter=adapter:node --install npm
cd northwilds-site
rm src/routes/+page.svelte
```

- The Node adapter builds a server you start with `node build`. Any adapter with a server works; a static build cannot preview drafts or receive webhooks.
- `src/routes/+page.svelte` is removed because the page route in step 5 also answers `/`.

## 2. Install the SDK

```bash
npm install @bifrost-orbit-cms/sdk
```

The client needs only `fetch`, so it runs in SvelteKit's server code without anything else.

## 3. Add the settings

Create `.env` in the root of the project. The project's `.gitignore` already leaves it out of Git.

```bash
# .env
CMS_API_URL=https://api.bifrostorbit.com/cms
CMS_PUBLIC_KEY=cms_pk_...
CMS_PREVIEW_KEY=cms_sk_...
CMS_WEBHOOK_SECRET=whsec_...
CMS_DEFAULT_REGION=global
```

SvelteKit 3 reads environment variables that you declare in `src/env.ts`:

```ts
// src/env.ts
import { defineEnvVars } from '@sveltejs/kit/env'

const optional = (value: string | undefined) => value || undefined

export const variables = defineEnvVars({
  CMS_API_URL: {},
  CMS_PUBLIC_KEY: {},
  CMS_PREVIEW_KEY: { schema: optional },
  CMS_WEBHOOK_SECRET: { schema: optional },
  CMS_DEFAULT_REGION: {},
})
```

None of them is marked `public`, so they can only be imported from `$app/env/private`, which SvelteKit refuses to send to the browser. The secret key and the webhook secret are optional, so the live website can run without them.

## 4. Create the client

```ts
// src/lib/server/cms.ts
import { createCmsClient, type CmsResolution } from '@bifrost-orbit-cms/sdk'
import { CMS_API_URL, CMS_DEFAULT_REGION, CMS_PREVIEW_KEY, CMS_PUBLIC_KEY } from '$app/env/private'

export const cms = createCmsClient({
  baseUrl: CMS_API_URL,
  apiKey: CMS_PUBLIC_KEY,
  previewKey: CMS_PREVIEW_KEY,
  defaultRegion: CMS_DEFAULT_REGION,
})

const MAX_AGE_MS = 60_000
const pages = new Map<string, { at: number; result: Promise<CmsResolution> }>()

export function resolvePage(path: string, preview: boolean): Promise<CmsResolution> {
  if (preview) return cms.resolve({ path, preview: true })
  const cached = pages.get(path)
  if (cached && Date.now() - cached.at < MAX_AGE_MS) return cached.result
  const result = cms.resolve({ path })
  pages.set(path, { at: Date.now(), result })
  result.catch(() => pages.delete(path))
  return result
}

export function purge(path?: string) {
  if (path) pages.delete(path)
  else pages.clear()
}
```

- Files in `src/lib/server` are server-only: SvelteKit fails the build if browser code imports them, so the secret key cannot leak.
- SvelteKit has no data cache of its own, so `resolvePage` keeps published pages in memory for 60 seconds. Drafts are never cached. `purge` is what the webhook in step 8 calls.
- The memory cache belongs to one server process. If the website runs on several servers, keep the answers in a shared cache, such as Redis, and purge it there.

## 5. Show a page

One catch-all route answers every address. `[...path]` also matches `/`, with an empty `path`.

```ts
// src/routes/[...path]/+page.server.ts
import { error, redirect } from '@sveltejs/kit'
import { resolvePage } from '#lib/server/cms.ts'
import type { PageServerLoad } from './$types'

export const load: PageServerLoad = async ({ params, locals }) => {
  const result = await resolvePage('/' + params.path, locals.preview)

  if (result.kind === 'redirect') redirect(result.status, result.to)
  if (result.kind === 'gone') error(410, 'This page has been removed')
  if (result.kind === 'notFound') error(404, 'Page not found')

  return { page: result.page }
}
```

`resolve` answers with the page, or with what to do instead: a redirect with its own status (such as 308 for a page that moved), `gone` for a deleted page and `notFound` for an unknown address. `locals.preview` is set in step 7; until then, add the type so the project compiles:

```ts
// src/app.d.ts
declare global {
  namespace App {
    interface Locals {
      preview: boolean
    }
  }
}

export {}
```

The page sets its title, description and canonical address from the page's SEO fields, then draws its components:

```svelte
<!-- src/routes/[...path]/+page.svelte -->
<script lang="ts">
  import Blocks from '#lib/blocks/Blocks.svelte'
  import type { PageProps } from './$types'

  let { data }: PageProps = $props()
  const page = $derived(data.page)
</script>

<svelte:head>
  <title>{page.seo.title}</title>
  <meta name="description" content={page.seo.description} />
  <link rel="canonical" href={page.seo.canonical} />
</svelte:head>

<main>
  <Blocks blocks={page.components} />
</main>
```

The error page shows for 404 and 410:

```svelte
<!-- src/routes/+error.svelte -->
<script lang="ts">
  import { page } from '$app/state'
</script>

<svelte:head>
  <title>{page.status} | Northwilds</title>
</svelte:head>

<main>
  <h1>{page.status === 404 ? 'We could not find that page' : 'Something went wrong'}</h1>
  <p><a href="/">Back to the home page</a></p>
</main>
```

New SvelteKit 3 projects import from `src/lib` with `#lib/…`. Add the `.ts` extension when you import a TypeScript file this way, as above; Svelte files already have theirs.

## 6. Write and register components

Each component an editor can place on a page gets a Svelte component. Open **Configuration › Components** to see your space's component keys and fields. This guide draws a `hero`, a `featureGrid` with `featureItem` cards in its `items` slot, and the `action` buttons inside the hero. Use your own keys and fields.

The registry maps each component key to its Svelte component:

```ts
// src/lib/blocks/registry.ts
import type { Component } from 'svelte'
import type { CmsComponent } from '@bifrost-orbit-cms/sdk'
import Action from './Action.svelte'
import FeatureGrid from './FeatureGrid.svelte'
import FeatureItem from './FeatureItem.svelte'
import Hero from './Hero.svelte'

export type BlockProps = { block: CmsComponent }

export const registry: Record<string, Component<BlockProps>> = {
  hero: Hero,
  featureGrid: FeatureGrid,
  featureItem: FeatureItem,
  action: Action,
}
```

`Blocks` draws a list of blocks with the registry. Every component uses it for its nested blocks too:

```svelte
<!-- src/lib/blocks/Blocks.svelte -->
<script lang="ts">
  import type { CmsComponent } from '@bifrost-orbit-cms/sdk'
  import Fallback from './Fallback.svelte'
  import { registry } from './registry'

  let { blocks = [] }: { blocks?: CmsComponent[] } = $props()
</script>

{#each blocks as block (block.id)}
  {@const Block = registry[block.type] ?? Fallback}
  <Block {block} />
{/each}
```

A block with no component yet shows its type while you develop, and nothing on the live website:

```svelte
<!-- src/lib/blocks/Fallback.svelte -->
<script lang="ts">
  import { dev } from '$app/env'
  import type { BlockProps } from './registry'

  let { block }: BlockProps = $props()
</script>

{#if dev}
  <div data-cms-id={block.id} style="border: 1px dashed; padding: 1rem">
    No component for <code>{block.type}</code> yet
  </div>
{/if}
```

The hero. Its buttons are blocks in the `primaryAction` and `secondaryAction` slots:

```svelte
<!-- src/lib/blocks/Hero.svelte -->
<script lang="ts">
  import Blocks from './Blocks.svelte'
  import type { BlockProps } from './registry'

  type HeroFields = { eyebrow?: string; heading: string; description?: string }

  let { block }: BlockProps = $props()
  const fields = $derived(block.fields as HeroFields)
  const actions = $derived([...(block.children.primaryAction ?? []), ...(block.children.secondaryAction ?? [])])
</script>

<section data-cms-id={block.id} class="hero">
  {#if fields.eyebrow}<p>{fields.eyebrow}</p>{/if}
  <h1>{fields.heading}</h1>
  {#if fields.description}{@html fields.description}{/if}
  <Blocks blocks={actions} />
</section>
```

```svelte
<!-- src/lib/blocks/Action.svelte -->
<script lang="ts">
  import type { CmsLink } from '@bifrost-orbit-cms/sdk'
  import type { BlockProps } from './registry'

  type ActionFields = { label: string; link?: CmsLink | null }

  let { block }: BlockProps = $props()
  const fields = $derived(block.fields as ActionFields)
</script>

{#if fields.link?.href}
  <a data-cms-id={block.id} href={fields.link.href} target={fields.link.target ?? undefined}>{fields.label}</a>
{/if}
```

The feature grid and its cards:

```svelte
<!-- src/lib/blocks/FeatureGrid.svelte -->
<script lang="ts">
  import Blocks from './Blocks.svelte'
  import type { BlockProps } from './registry'

  type FeatureGridFields = { heading: string; intro?: string }

  let { block }: BlockProps = $props()
  const fields = $derived(block.fields as FeatureGridFields)
</script>

<section data-cms-id={block.id} class="feature-grid">
  <h2>{fields.heading}</h2>
  {#if fields.intro}<p>{fields.intro}</p>{/if}
  <div class="grid">
    <Blocks blocks={block.children.items} />
  </div>
</section>
```

```svelte
<!-- src/lib/blocks/FeatureItem.svelte -->
<script lang="ts">
  import type { CmsLink } from '@bifrost-orbit-cms/sdk'
  import type { BlockProps } from './registry'

  type FeatureItemFields = { title: string; body?: string; link?: CmsLink | null }

  let { block }: BlockProps = $props()
  const fields = $derived(block.fields as FeatureItemFields)
</script>

<article data-cms-id={block.id}>
  <h3>{fields.title}</h3>
  {#if fields.body}<p>{fields.body}</p>{/if}
  {#if fields.link?.href}<a href={fields.link.href}>Read more</a>{/if}
</article>
```

- **Fields** are on `block.fields`. Rich text, such as the hero's `description`, arrives as HTML. Links carry `href`, which is `null` when the link points at a page that is not live, so check it first.
- **Nested blocks** are on `block.children`, one list per slot, such as `block.children.items`. Each nested block has the same shape, so `Blocks` draws it with the registry.
- **`data-cms-id={block.id}`** on each component's outer element lets editors click it in the live preview to select it.
- To type fields from your space's schema instead of by hand, run `npx cms-orbit generate --out src/lib/cms-types.ts`, which reads the API address and public key from `.env`, and use the types it writes, such as `HeroBlock`; see [The SDK](https://docs.bifrostorbit.com/cms/developers/sdk/).

**Check it:** run `npm run dev` and open `http://localhost:5173/`. The home page shows its hero and the rest of its blocks, a nested page such as `/products/cms-orbit` works the same way, and an unknown address shows the 404 page.

## 7. Preview drafts in the editor

The editor opens your page in a frame with a short-lived token, such as `https://stage.northwilds.com/trips/lofoten-kayak?preview=eyJ…`. Your website checks the token with CMS Orbit, remembers it in a cookie, and then reads drafts with the secret key.

```ts
// src/lib/server/preview.ts
export const PREVIEW_COOKIE = 'cms_preview'

export function safePath(path: string | null): string {
  return path && path.startsWith('/') && !path.startsWith('//') && !path.includes('\\') ? path : '/'
}
```

`cms.checkPreview(token)` asks CMS Orbit whether a token is valid and which page it belongs to. `safePath` keeps redirects on your own website.

**The preview endpoint** checks the token, sets the cookie and goes to the page:

```ts
// src/routes/api/preview/+server.ts
import { error, redirect } from '@sveltejs/kit'
import { cms } from '#lib/server/cms.ts'
import { PREVIEW_COOKIE, safePath } from '#lib/server/preview.ts'
import type { RequestHandler } from './$types'

export const GET: RequestHandler = async ({ url, cookies }) => {
  const token = url.searchParams.get('preview') ?? url.searchParams.get('token')
  if (!token) error(400, 'A preview token is required')
  const preview = await cms.checkPreview(token)
  if (!preview.valid) error(401, 'That preview link is invalid or has expired')

  cookies.set(PREVIEW_COOKIE, token, { path: '/', httpOnly: true, secure: true, sameSite: 'none', maxAge: 60 * 60 })
  redirect(307, safePath(url.searchParams.get('path') ?? preview.path))
}
```

The cookie is `SameSite=None` and `Secure` because the editor shows your website in a frame on another site. Without a `path`, it goes to the token's own page. Tokens last an hour, and the editor makes new ones as needed.

**The exit endpoint** leaves preview, for a "Leave preview" link such as `/api/preview/exit?path=/trips`:

```ts
// src/routes/api/preview/exit/+server.ts
import { redirect } from '@sveltejs/kit'
import { PREVIEW_COOKIE, safePath } from '#lib/server/preview.ts'
import type { RequestHandler } from './$types'

export const GET: RequestHandler = ({ url, cookies }) => {
  cookies.delete(PREVIEW_COOKIE, { path: '/', secure: true, sameSite: 'none' })
  redirect(307, safePath(url.searchParams.get('path')))
}
```

**The server hook** sends the editor's `?preview=` links to the preview endpoint, keeping the page's address, and sets `locals.preview` on every request:

```ts
// src/hooks.server.ts
import type { Handle } from '@sveltejs/kit/hooks'
import { cms } from '#lib/server/cms.ts'
import { PREVIEW_COOKIE } from '#lib/server/preview.ts'

export const handle: Handle = async ({ event, resolve }) => {
  const token = event.url.searchParams.get('preview')
  if (token && !event.url.pathname.startsWith('/api/')) {
    const target = new URLSearchParams({ preview: token, path: event.url.pathname })
    return new Response(null, { status: 307, headers: { location: `/api/preview?${target}` } })
  }

  const { valid } = await cms.checkPreview(event.cookies.get(PREVIEW_COOKIE))
  event.locals.preview = valid
  return resolve(event)
}
```

The token in the cookie is checked again on each request, so a copied or expired cookie never shows drafts. Visitors without the cookie pay nothing extra: without a token, `checkPreview` answers without asking CMS Orbit. With `locals.preview` on, the load function in step 5 calls `resolve` with `preview: true`, which reads the draft with the secret key and skips the cache.

**The bridge** lets editors click a block in the preview to select it, and reloads the preview after each save. Load it only while previewing:

```ts
// src/routes/+layout.server.ts
import { cms } from '#lib/server/cms.ts'
import type { LayoutServerLoad } from './$types'

export const load: LayoutServerLoad = ({ locals }) => ({
  preview: locals.preview,
  bridge: `${cms.origin}/bridge.js`,
})
```

```svelte
<!-- src/routes/+layout.svelte -->
<script lang="ts">
  import favicon from '#lib/assets/favicon.svg'
  import type { LayoutProps } from './$types'

  let { data, children }: LayoutProps = $props()
</script>

<svelte:head>
  <link rel="icon" href={favicon} />
  {#if data.preview}
    <script src={data.bridge} defer></script>
  {/if}
</svelte:head>

{@render children()}
```

The bridge selects the nearest element with `data-cms-id`, which every component from step 6 has.

**Tell CMS Orbit where the website is:** open the space's **Settings** and set **Preview URL** to the website that has the secret key, such as `https://stage.northwilds.com`. The editor adds each page's address after it.

**Check it:** open a page in the editor, change a heading and save without publishing. The preview reloads with the change. Click a block in the preview, and the editor selects it.

> **Note:** The editor frames your website from another site, so the cookie only works inside the frame over `https`, and browsers that block third-party cookies may drop it. If the preview shows the published page, use **Open in a new tab** above the preview. To show changes as editors type, without a reload, listen to the bridge yourself; see **Show changes as editors type** in [Set up the live preview](https://docs.bifrostorbit.com/cms/developers/preview/).

## 8. Refresh when editors publish

Without this step, a published change appears within 60 seconds, when the cached page expires. With it, CMS Orbit tells your website the moment an editor publishes, and only that page is fetched again.

```ts
// src/routes/api/cms-webhook/+server.ts
import { verifyWebhook } from '@bifrost-orbit-cms/sdk'
import { CMS_WEBHOOK_SECRET } from '$app/env/private'
import { purge } from '#lib/server/cms.ts'
import type { RequestHandler } from './$types'

export const POST: RequestHandler = async ({ request }) => {
  if (!CMS_WEBHOOK_SECRET) return new Response(null, { status: 401 })

  const result = await verifyWebhook({
    body: await request.text(),
    timestamp: request.headers.get('x-orbit-timestamp'),
    signature: request.headers.get('x-orbit-signature'),
    secret: CMS_WEBHOOK_SECRET,
  })
  if (!result.valid) return new Response(null, { status: 401 })

  const { event, data } = result
  if (event === 'webhook.test') return new Response(null, { status: 204 })

  const url = typeof data.url === 'string' ? data.url : null
  const moved = typeof data.previousUrl === 'string' && data.previousUrl !== url
  if (event.startsWith('content.') && url && !moved) purge(url)
  else purge()

  return new Response(null, { status: 204 })
}
```

- `verifyWebhook` checks the signature in constant time against the raw body, read as text so the bytes match, and refuses messages more than five minutes old. Both answer `401`, as does a website without a webhook secret.
- It parses the body too, so `result.event` and `result.data` are ready to use.
- A published page purges its own address. A moved page, a menu, a release or anything without an address purges everything, since links on other pages may have changed.
- Any `2xx` answer counts as delivered. Answer quickly and do slow work afterwards.

**Create the webhook:**

1. Deploy the website, so the endpoint has a public `https` address. Build with `npm run build` and start it with `node --env-file=.env build`, or set the same variables where it runs.
2. Open **Configuration › Webhooks** and select **New webhook**. **Address:** `https://northwilds.com/api/cms-webhook`. **Environment:** Production. Keep the default events and tick **Page deleted** and **Release published** too.
3. Copy the secret that starts with `whsec_` into `CMS_WEBHOOK_SECRET` where the website runs, and restart it.

**Check it:** in the webhook's **⋯** menu, select **Send a test**. CMS Orbit shows that the website answered `204`. Then publish a change and reload the page: the change is there straight away.

## Next steps

- [Render components](https://docs.bifrostorbit.com/cms/developers/render-blocks/): fields, images, links, slots, variants and shared sections.
- [Set up the live preview](https://docs.bifrostorbit.com/cms/developers/preview/): marking the header and footer, and showing changes as editors type.
- [Refresh the website when content changes](https://docs.bifrostorbit.com/cms/developers/webhooks/) and [Caching and refreshing pages](https://docs.bifrostorbit.com/cms/developers/caching-and-refresh/).
- [Regions and languages](https://docs.bifrostorbit.com/cms/developers/regions-and-languages/): several regions and languages, and how to ask for them.
- [Connect a website without Next.js](https://docs.bifrostorbit.com/cms/developers/connect-any-website/), [The SDK](https://docs.bifrostorbit.com/cms/developers/sdk/) and [Metadata, sitemaps and robots with the SDK](https://docs.bifrostorbit.com/cms/developers/seo-with-the-sdk/).
- [Troubleshooting your website](https://docs.bifrostorbit.com/cms/developers/troubleshooting/).
