# Nuxt quickstart

> A Nuxt website that renders every CMS Orbit page at its own address with Vue components, previews drafts through a server route and clears its cache when editors publish.

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

In about 15 minutes you build a Nuxt 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 Vue component of yours, editors see their drafts in the live preview, and publishing clears the cached page straight away.

The keys stay on the server: pages read CMS Orbit through one server route of your own, which caches published pages and reads drafts. The SDK's core client is all you need: React is not.

**Tested with:** Nuxt 4.6.4 (Nitro 2.13), Vue 3.5.45, `@bifrost-orbit-cms/sdk` 0.12.0, Node.js 24.

Prefer to start from a working project? Use the starter: [bifrost-orbit/cms-starter-nuxt](https://github.com/bifrost-orbit/cms-starter-nuxt), 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 22.22 or later, or 24.15 or later**, which Nuxt 4 needs.

## 1. Create the project

```bash
npm create nuxt@latest northwilds-site -- --template minimal --packageManager npm --gitInit=false --no-modules
cd northwilds-site
```

## 2. Install the SDK

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

## 3. Add the settings

```bash
# .env
NUXT_CMS_API_URL=https://api.bifrostorbit.com/cms
NUXT_CMS_PUBLIC_KEY=cms_pk_...
NUXT_CMS_PREVIEW_KEY=cms_sk_...
NUXT_CMS_DEFAULT_REGION=global
NUXT_CMS_WEBHOOK_SECRET=
```

Use your own region key. `NUXT_CMS_WEBHOOK_SECRET` stays empty until step 8. Nuxt keeps `.env` out of git.

Declare them as server settings in `nuxt.config.ts`. Nuxt fills each one from the environment variable with the `NUXT_` prefix when the server starts, so the built website holds no keys:

```ts
// nuxt.config.ts
export default defineNuxtConfig({
  compatibilityDate: '2025-07-15',
  devtools: { enabled: true },
  runtimeConfig: {
    cmsApiUrl: '',
    cmsPublicKey: '',
    cmsPreviewKey: '',
    cmsWebhookSecret: '',
    cmsDefaultRegion: 'global',
  },
})
```

Keep them out of `runtimeConfig.public`, which is sent to the browser.

## 4. Create the client

Files in `server/utils` are available to every server route without an import:

```ts
// server/utils/cms.ts
import { createCmsClient, type CmsClient } from '@bifrost-orbit-cms/sdk'

let client: CmsClient | undefined

export function useCms(): CmsClient {
  const config = useRuntimeConfig()
  client ??= createCmsClient({
    baseUrl: config.cmsApiUrl,
    apiKey: config.cmsPublicKey,
    previewKey: config.cmsPreviewKey || undefined,
    defaultRegion: config.cmsDefaultRegion,
  })
  return client
}

export const pageCacheKey = (region: string, path: string) => encodeURIComponent(region + path)

export const resolvePublished = defineCachedFunction(
  (region: string, path: string) => useCms().resolve({ region, path }),
  { name: 'cms-page', maxAge: 60, swr: true, getKey: pageCacheKey },
)

export async function isPreviewToken(token: unknown): Promise<boolean> {
  if (typeof token !== 'string' || !useRuntimeConfig().cmsPreviewKey) return false
  return (await useCms().checkPreview(token)).valid
}
```

- `resolvePublished` keeps each published answer in Nitro's cache for 60 seconds, and serves the old one while it fetches a new one after that. The webhook in step 8 clears it by `pageCacheKey`.
- `isPreviewToken` is used in step 7.

## 5. Show a page

**The server route** is the only place that talks to CMS Orbit:

```ts
// server/api/cms/page.get.ts
export default defineEventHandler(async (event) => {
  const query = getQuery(event)
  const path = typeof query.path === 'string' && query.path.startsWith('/') ? query.path : '/'
  const region = useRuntimeConfig().cmsDefaultRegion

  if (await isPreviewToken(query.preview)) {
    const result = await useCms().resolve({ region, path, preview: true })
    return { result, bridge: `${useCms().origin}/bridge.js` }
  }
  return { result: await resolvePublished(region, path), bridge: null }
})
```

**One catch-all page** answers every address. During server rendering, `useFetch` calls the route directly, without a network request; after that, Nuxt reads the next page through it as visitors click around:

```vue
<!-- app/pages/[...slug].vue -->
<script setup lang="ts">
const route = useRoute()
const slug = route.params.slug
const path = '/' + (Array.isArray(slug) ? slug.join('/') : slug || '')

const { data } = await useFetch('/api/cms/page', { query: { path, preview: route.query.preview } })
const result = data.value?.result

if (!result || result.kind === 'notFound') throw createError({ statusCode: 404, statusMessage: 'Page not found' })
if (result.kind === 'gone') throw createError({ statusCode: 410, statusMessage: 'Page removed' })
if (result.kind === 'redirect') await navigateTo(result.to, { redirectCode: result.status, external: !result.to.startsWith('/') })

const page = result.kind === 'page' ? result.page : null
const bridge = data.value?.bridge

if (page) {
  useSeoMeta({ title: page.seo.title, description: page.seo.description })
  useHead({ htmlAttrs: { lang: page.locale }, script: bridge ? [{ src: bridge, defer: true }] : [] })
}
</script>

<template>
  <main v-if="page">
    <CmsBlock v-for="block in page.components" :key="block.id" :block="block" />
  </main>
</template>
```

- `resolve` answers with the page, a redirect (such as a page whose address changed), `gone` for a deleted page or `notFound`.
- `createError` shows `app/error.vue` with that status, and `navigateTo` sends the redirect with its own status.
- `page.seo` also holds the canonical address, robots, Open Graph and hreflang alternates when you want more tags; see [Metadata, sitemaps and robots with the SDK](https://docs.bifrostorbit.com/cms/developers/seo-with-the-sdk/).

Replace `app/app.vue`, and add the error page:

```vue
<!-- app/app.vue -->
<template>
  <NuxtPage />
</template>
```

```vue
<!-- app/error.vue -->
<script setup lang="ts">
import type { NuxtError } from '#app'

const props = defineProps<{ error: NuxtError }>()
useSeoMeta({ title: props.error.statusCode === 404 ? 'Page not found · Northwilds' : 'Something went wrong · Northwilds' })
</script>

<template>
  <main>
    <h1 v-if="error.statusCode === 404">We couldn't find that page</h1>
    <h1 v-else>Something went wrong</h1>
    <p><NuxtLink to="/">Back to the home page</NuxtLink></p>
  </main>
</template>
```

## 6. Write and register components

Generate types for your space's components, so each Vue component knows its fields:

```bash
npx cms-orbit generate --out app/cms/types.ts
```

It reads `NUXT_CMS_API_URL` and `NUXT_CMS_PUBLIC_KEY` from `.env` and prints something like `Wrote 60 components and 10 content types to app/cms/types.ts`. Run it again when a developer changes a component in CMS Orbit.

**One component looks up the rest.** `CmsBlock` finds the component for each block's `type`, and shows a note for types you have not written yet while you develop. Components in `app/components` can be used in any template without an import:

```vue
<!-- app/components/CmsBlock.vue -->
<script setup lang="ts">
import type { CmsComponent } from '@bifrost-orbit-cms/sdk'
import { registry } from '~/cms/registry'

const props = defineProps<{ block: CmsComponent }>()
const component = computed(() => registry[props.block.type])
const dev = import.meta.dev
</script>

<template>
  <component :is="component" v-if="component" :block="block" />
  <p v-else-if="dev" :data-cms-id="block.id">No component for <code>{{ block.type }}</code> yet.</p>
</template>
```

In production an unknown block renders nothing, so a new component in CMS Orbit never breaks the page.

**The registry** maps each type to your component. The keys are the component keys in your space:

```ts
// app/cms/registry.ts
import type { Component } from 'vue'
import Action from './blocks/Action.vue'
import FeatureSpotlight from './blocks/FeatureSpotlight.vue'
import Hero from './blocks/Hero.vue'

export const registry: Record<string, Component> = {
  action: Action,
  featureSpotlight: FeatureSpotlight,
  hero: Hero,
}
```

**The components.** Each gets the block as `block`, with its values in `block.fields`. Rich text arrives as HTML, so it is set with `v-html`. Put `:data-cms-id="block.id"` on the outer element, so editors can click the block in the preview.

A hero with a heading, an introduction and up to two buttons. The buttons are blocks nested in the hero's slots, so they are drawn with `CmsBlock` too:

```vue
<!-- app/cms/blocks/Hero.vue -->
<script setup lang="ts">
import type { CmsNode } from '@bifrost-orbit-cms/sdk'
import type { HeroBlock } from '~/cms/types'

defineProps<{ block: CmsNode<HeroBlock> }>()
</script>

<template>
  <section :data-cms-id="block.id" class="hero">
    <p v-if="block.fields.eyebrow" class="eyebrow">{{ block.fields.eyebrow }}</p>
    <h1>{{ block.fields.heading }}</h1>
    <div v-if="block.fields.description" v-html="block.fields.description" />
    <div class="actions">
      <CmsBlock v-if="block.fields.primaryAction" :block="block.fields.primaryAction" />
      <CmsBlock v-if="block.fields.secondaryAction" :block="block.fields.secondaryAction" />
    </div>
  </section>
</template>
```

A feature section with an optional image. `cmsImageSrcSet` lists resized copies, so browsers download the smallest that fits:

```vue
<!-- app/cms/blocks/FeatureSpotlight.vue -->
<script setup lang="ts">
import { cmsImageSrcSet, type CmsNode } from '@bifrost-orbit-cms/sdk'
import type { FeatureSpotlightBlock } from '~/cms/types'

defineProps<{ block: CmsNode<FeatureSpotlightBlock> }>()
</script>

<template>
  <section :data-cms-id="block.id" class="spotlight">
    <p v-if="block.fields.eyebrow" class="eyebrow">{{ block.fields.eyebrow }}</p>
    <h2>{{ block.fields.heading }}</h2>
    <div v-if="block.fields.body" v-html="block.fields.body" />
    <img
      v-if="block.fields.image"
      :src="block.fields.image.url"
      :srcset="cmsImageSrcSet(block.fields.image.url, block.fields.image.width)"
      sizes="(min-width: 768px) 50vw, 100vw"
      :width="block.fields.image.width ?? undefined"
      :height="block.fields.image.height ?? undefined"
      :alt="block.fields.image.alt"
      loading="lazy"
    >
    <CmsBlock v-if="block.fields.action" :block="block.fields.action" />
  </section>
</template>
```

The button itself. A link to a page carries the page's current address in `href`, and `null` when that page is not published. `NuxtLink` moves between your own pages without a full reload and opens other addresses as normal links:

```vue
<!-- app/cms/blocks/Action.vue -->
<script setup lang="ts">
import type { CmsNode } from '@bifrost-orbit-cms/sdk'
import type { ActionBlock } from '~/cms/types'

defineProps<{ block: CmsNode<ActionBlock> }>()
</script>

<template>
  <NuxtLink
    v-if="block.fields.link?.href"
    :data-cms-id="block.id"
    :class="['button', block.fields.style ?? 'primary']"
    :to="block.fields.link.href"
    :target="block.fields.link.target ?? undefined"
  >
    {{ block.fields.label }}
  </NuxtLink>
  <span v-else :data-cms-id="block.id" :class="['button', block.fields.style ?? 'primary']">{{ block.fields.label }}</span>
</template>
```

Your space's components have their own keys and fields: `app/cms/types.ts` lists them. Start the website and open it:

```bash
npm run dev
```

`http://localhost:3000/` shows the home page, with a note for each component you have not written yet. An address with no page, such as `/no-such-page`, shows your error page with a `404`.

## 7. Preview drafts in the editor

The editor shows your website beside it, at the space's **Preview URL** followed by the page's address and a preview token, such as `https://stage.northwilds.com/trips/lofoten-kayak?preview=eyJ…`.

Step 4 and step 5 already handle it:

1. The page passes `preview` from its address to the server route.
2. `isPreviewToken` asks CMS Orbit with `checkPreview` whether the token is valid.
3. The route then reads the draft with `preview: true`, which sends the secret key and asks for drafts, and skips the cache, so drafts are never shown to visitors.
4. The page adds the bridge script, so editors can click a block to select it, and the preview reloads after each save.
5. `data-cms-id` on each component's outer element tells the bridge which block is which.

The token stays in the address, so a reload after each save is still a preview, and nothing is stored in a cookie. Each token lasts an hour, and the editor makes new ones as needed. The secret key never leaves the server: the browser only ever sees the token and the draft.

To try it, build and start the website, set **Preview URL** in the space's **Settings** to its address, and open a page in the editor:

```bash
npm run build
node --env-file=.env .output/server/index.mjs
```

The editor must be able to show your website in a frame, so the preview needs `https` once it is deployed; see [Deploy your website](https://docs.bifrostorbit.com/cms/developers/deploy-your-website/). Drafts are previewed against Staging, so run a staging copy of the website with keys from the Staging environment. To show changes as editors type rather than after each save, see **Show changes as editors type** in [Set up the live preview](https://docs.bifrostorbit.com/cms/developers/preview/).

## 8. Refresh when editors publish

Published pages are cached for up to a minute. A webhook clears a page the moment it is published.

```ts
// server/api/cms-webhook.post.ts
import { verifyWebhook } from '@bifrost-orbit-cms/sdk'

export default defineEventHandler(async (event) => {
  const secret = useRuntimeConfig().cmsWebhookSecret
  const result = secret && await verifyWebhook({
    body: (await readRawBody(event, 'utf8')) ?? '',
    timestamp: getHeader(event, 'x-orbit-timestamp'),
    signature: getHeader(event, 'x-orbit-signature'),
    secret,
  })
  if (!result || !result.valid) {
    setResponseStatus(event, 401)
    return null
  }

  const { event: name, data } = result
  const { url, region } = data
  const cache = useStorage('cache')
  const onePage = name.startsWith('content.') && typeof url === 'string' && typeof region === 'string' && !data.previousUrl && data.contentType !== 'sharedSection'
  if (onePage) await cache.removeItem(`nitro:functions:cms-page:${pageCacheKey(region, url)}.json`)
  else if (name !== 'webhook.test') await cache.clear('nitro:functions:cms-page')

  setResponseStatus(event, 204)
  return null
})
```

- `readRawBody` gives the body exactly as it was sent. `verifyWebhook` checks its signature against the webhook secret in constant time, refuses messages more than five minutes old and reads the event from the body. Until the secret is set, the route refuses every message.
- A published, unpublished or deleted page clears only that page. A page that moved, a shared section, a menu or anything else clears every cached page, since any page may show it. A test message clears nothing.
- The cache key uses the region's key, which is what the webhook sends, so set `NUXT_CMS_DEFAULT_REGION` to the key, not the short code.

Then register it:

1. Open **Configuration › Webhooks** and select **New webhook**. **Address:** `https://northwilds.com/api/cms-webhook`. **Environment:** Production. Also tick **Page deleted** and **Release published**.
2. Copy the secret that starts with `whsec_` into `NUXT_CMS_WEBHOOK_SECRET` and restart the server.
3. In the webhook's **⋯** menu, select **Send a test**. The CMS shows that the website answered `204`.

Nitro's cache is kept in the server's memory by default. If you run several copies of the website, mount a shared store for `cache`, such as Redis, under `nitro.storage` in `nuxt.config.ts`, so one webhook clears it for all of them.

## Next steps

- [Connect a website without Next.js](https://docs.bifrostorbit.com/cms/developers/connect-any-website/): plain HTTP, GraphQL, and preview and refresh in any framework.
- [Render components](https://docs.bifrostorbit.com/cms/developers/render-blocks/): every field type, 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 [Events and webhooks](https://docs.bifrostorbit.com/cms/developers/events/).
- [Regions and languages](https://docs.bifrostorbit.com/cms/developers/regions-and-languages/): several regions on one domain.
- [Metadata, sitemaps and robots with the SDK](https://docs.bifrostorbit.com/cms/developers/seo-with-the-sdk/) and [The SDK](https://docs.bifrostorbit.com/cms/developers/sdk/).
- [Troubleshooting your website](https://docs.bifrostorbit.com/cms/developers/troubleshooting/).
