Skip to content

Vue quickstart (Vite and Vue Router)

A client-rendered Vue website with Vite and Vue Router that shows every CMS Orbit page at its own address, with a small server for draft previews.

Tutorial12 min read

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

The website is client-rendered: the browser reads published pages straight from CMS Orbit with the public key. Drafts need the secret key, which must never reach the browser, so previews go through a small server of your own. You write it in step 7, in about 60 lines of Node.js.

A client-rendered website sends search engines an empty page first, and its not found page answers 200. If those matter, render on the server, as in the Nuxt quickstart.

Tested with: Vue 3.5.45, Vue Router 5.4, Vite 8.3, @bifrost-orbit-cms/sdk 0.12.0, Node.js 24.

Prefer to start from a working project? Use the starter: bifrost-orbit/cms-starter-vue, 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 website and a secret cms_sk_ key with Read drafts on, for previews. Step 4 of Connect a website to CMS Orbit 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.18 or later, or 24.12 or later. The preview server in step 7 is TypeScript that Node.js runs as it is.

1Create the project

Shell
npm create vue@latest northwilds-site -- --ts --router --barecd northwilds-sitenpm install

src/main.ts stays as it is: it mounts App.vue with the router.

2Install the SDK

Shell
npm install @bifrost-orbit-cms/sdk

3Add the settings

.envShell
VITE_CMS_API_URL=https://api.bifrostorbit.com/cmsVITE_CMS_PUBLIC_KEY=cms_pk_...VITE_CMS_DEFAULT_REGION=globalCMS_PREVIEW_KEY=cms_sk_...CMS_WEBHOOK_SECRET=

Vite copies settings that start with VITE_ into the browser bundle, and only those. The public key may go there: it can only read published content. The secret key has no VITE_ prefix, so only the preview server reads it. Add .env to .gitignore, since it holds the secret key.

Tell TypeScript about the browser settings:

env.d.tsTypeScript
/// <reference types="vite/client" />interface ImportMetaEnv {  readonly VITE_CMS_API_URL: string  readonly VITE_CMS_PUBLIC_KEY: string  readonly VITE_CMS_DEFAULT_REGION: string}

Send /api to the preview server while you develop, by replacing vite.config.ts:

vite.config.tsTypeScript
import { fileURLToPath, URL } from 'node:url'import { defineConfig } from 'vite'import vue from '@vitejs/plugin-vue'import vueDevTools from 'vite-plugin-vue-devtools'export default defineConfig({  plugins: [vue(), vueDevTools()],  resolve: {    alias: {      '@': fileURLToPath(new URL('./src', import.meta.url)),    },  },  server: {    proxy: { '/api': 'http://localhost:3030' },  },})

4Create the client

src/cms/client.tsTypeScript
import { createCmsClient, type CmsResolution } from '@bifrost-orbit-cms/sdk'export const cms = createCmsClient({  baseUrl: import.meta.env.VITE_CMS_API_URL,  apiKey: import.meta.env.VITE_CMS_PUBLIC_KEY,  defaultRegion: import.meta.env.VITE_CMS_DEFAULT_REGION,})export type LoadedPage = { result: CmsResolution; bridge: string | null }export async function loadPage(path: string, token: string | null): Promise<LoadedPage> {  if (token) {    const response = await fetch(`/api/preview-page?path=${encodeURIComponent(path)}&token=${encodeURIComponent(token)}`)    if (response.ok) return response.json()  }  return { result: await cms.resolve({ path }), bridge: null }}
  • In the browser the SDK puts the public key in the address, so our CDN answers repeated requests from its cache.
  • loadPage asks the preview server for the draft when there is a preview token, and CMS Orbit itself otherwise. If the token is refused, the published page is shown.

5Show a page

One route answers every address:

src/router/index.tsTypeScript
import { createRouter, createWebHistory } from 'vue-router'import CmsPageView from '@/views/CmsPageView.vue'const router = createRouter({  history: createWebHistory(import.meta.env.BASE_URL),  routes: [{ path: '/:slug(.*)*', component: CmsPageView }],})export default router
Vue
<!-- src/App.vue --><template>  <RouterView /></template>

The view loads the page whenever the address changes:

Vue
<!-- src/views/CmsPageView.vue --><script setup lang="ts">import { onBeforeUnmount, onMounted, ref, watch } from 'vue'import { useRoute, useRouter } from 'vue-router'import type { CmsPage } from '@bifrost-orbit-cms/sdk'import CmsBlock from '@/components/CmsBlock.vue'import { loadPage } from '@/cms/client'const route = useRoute()const router = useRouter()const page = ref<CmsPage | null>(null)const missing = ref(false)function setMeta(title: string, description = '') {  document.title = title  let tag = document.querySelector<HTMLMetaElement>('meta[name="description"]')  if (!tag) {    tag = document.createElement('meta')    tag.name = 'description'    document.head.append(tag)  }  tag.content = description}function addBridge(src: string) {  if (document.querySelector(`script[src="${src}"]`)) return  const script = document.createElement('script')  script.src = src  script.defer = true  document.head.append(script)}async function load(path: string) {  const token = typeof route.query.preview === 'string' ? route.query.preview : null  const { result, bridge } = await loadPage(path, token)  if (result.kind === 'redirect') {    if (result.to.startsWith('/')) router.replace(result.to)    else window.location.replace(result.to)    return  }  if (result.kind !== 'page') {    page.value = null    missing.value = true    setMeta('Page not found · Northwilds')    return  }  missing.value = false  page.value = result.page  document.documentElement.lang = result.page.locale  setMeta(result.page.seo.title, result.page.seo.description)  if (bridge) addBridge(bridge)}function refreshWhenVisible() {  if (document.visibilityState === 'visible') load(route.path)}watch(() => route.path, load, { immediate: true })onMounted(() => document.addEventListener('visibilitychange', refreshWhenVisible))onBeforeUnmount(() => document.removeEventListener('visibilitychange', refreshWhenVisible))</script><template>  <main v-if="page">    <CmsBlock v-for="block in page.components" :key="block.id" :block="block" />  </main>  <main v-else-if="missing">    <h1>We couldn't find that page</h1>    <p><RouterLink to="/">Back to the home page</RouterLink></p>  </main></template>
  • resolve answers with the page, a redirect (such as a page whose address changed), gone for a deleted page or notFound. Redirects to your own pages stay in the app.
  • The title, description and language come from page.seo and page.locale.
  • addBridge is for step 7, and refreshWhenVisible for step 8.

6Write and register components

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

Shell
npx cms-orbit generate --out src/cms/types.ts

It reads VITE_CMS_API_URL and VITE_CMS_PUBLIC_KEY from .env and prints something like Wrote 60 components and 10 content types to src/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:

Vue
<!-- src/components/CmsBlock.vue --><script setup lang="ts">import { computed } from 'vue'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.env.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:

src/cms/registry.tsTypeScript
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
<!-- src/cms/blocks/Hero.vue --><script setup lang="ts">import type { CmsNode } from '@bifrost-orbit-cms/sdk'import CmsBlock from '@/components/CmsBlock.vue'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
<!-- src/cms/blocks/FeatureSpotlight.vue --><script setup lang="ts">import { cmsImageSrcSet, type CmsNode } from '@bifrost-orbit-cms/sdk'import CmsBlock from '@/components/CmsBlock.vue'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. Addresses on your own website use RouterLink, so they open without a full reload:

Vue
<!-- src/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>  <RouterLink    v-if="block.fields.link?.href?.startsWith('/')"    :data-cms-id="block.id"    :class="['button', block.fields.style ?? 'primary']"    :to="block.fields.link.href"  >    {{ block.fields.label }}  </RouterLink>  <a    v-else-if="block.fields.link?.href"    :data-cms-id="block.id"    :class="['button', block.fields.style ?? 'primary']"    :href="block.fields.link.href"    :target="block.fields.link.target ?? undefined"  >    {{ block.fields.label }}  </a>  <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: src/cms/types.ts lists them. Start the website and open it:

Shell
npm run dev

http://localhost:5173/ 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 not found view.

7Preview 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…. The browser cannot read the draft itself, because that needs the secret key. It sends the token to your server instead:

server/preview.tsTypeScript
import { createServer, type IncomingMessage } from 'node:http'import { createCmsClient, verifyWebhook } from '@bifrost-orbit-cms/sdk'const cms = createCmsClient({  baseUrl: process.env.VITE_CMS_API_URL!,  apiKey: process.env.VITE_CMS_PUBLIC_KEY!,  previewKey: process.env.CMS_PREVIEW_KEY!,  defaultRegion: process.env.VITE_CMS_DEFAULT_REGION,})async function readBody(request: IncomingMessage): Promise<string> {  const chunks: Buffer[] = []  for await (const chunk of request) chunks.push(chunk)  return Buffer.concat(chunks).toString('utf8')}createServer(async (request, response) => {  const url = new URL(request.url ?? '/', 'http://localhost')  if (request.method === 'GET' && url.pathname === '/api/preview-page') {    if (!(await cms.checkPreview(url.searchParams.get('token'))).valid) {      response.writeHead(401).end()      return    }    const path = url.searchParams.get('path') ?? '/'    const result = await cms.resolve({ path: path.startsWith('/') ? path : '/', preview: true })    response.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' })    response.end(JSON.stringify({ result, bridge: `${cms.origin}/bridge.js` }))    return  }  if (request.method === 'POST' && url.pathname === '/api/cms-webhook') {    const secret = process.env.CMS_WEBHOOK_SECRET    const result = secret      ? await verifyWebhook({          body: await readBody(request),          timestamp: request.headers['x-orbit-timestamp']?.toString(),          signature: request.headers['x-orbit-signature']?.toString(),          secret,        })      : null    if (!result?.valid) {      response.writeHead(401).end()      return    }    console.log('CMS Orbit:', result.event, result.data.url ?? '')    response.writeHead(204).end()    return  }  response.writeHead(404).end()}).listen(Number(process.env.PORT ?? 3030))
  1. cms.checkPreview checks the token with CMS Orbit. If it is not valid, the server answers 401 and the view shows the published page.
  2. The server reads the draft with preview: true, which sends the secret key and asks for drafts, and returns it with the address of the bridge script.
  3. The view adds the bridge script, so editors can click a block to select it, and the preview reloads after each save. The token stays in the address, so the reload is still a preview.
  4. data-cms-id on each component's outer element tells the bridge which block is which.

The server's TypeScript needs Node.js types. Add the folder to tsconfig.node.json, in include:

JSON
"server/**/*"

Run it beside Vite, in a second terminal:

Shell
node --env-file-if-exists=.env server/preview.ts

The starter has this as npm run server. --env-file-if-exists reads .env when it is there and carries on without it when it is not, as on a production host where the settings are environment variables. Plain --env-file stops with an error when the file is missing.

To try it, set Preview URL in the space's Settings to the website's address and open a page in the editor.

When you deploy, build the website with npm run build and serve dist from any static host that answers every address with index.html. Run the preview server on the same domain under /api, for example behind the host's reverse proxy, so the browser reaches it at /api/preview-page. The editor must be able to show your website in a frame, so the preview needs https; see Deploy your website. Drafts are previewed against Staging, so run the preview on a staging copy 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.

8Refresh when editors publish

A client-rendered website has no page cache of its own to clear. Each visit reads the page from CMS Orbit, and CMS Orbit and our CDN drop their cached answers the moment something is published. So a published change shows on the next page load, within seconds, without a webhook.

What stays out of date is a tab that is already open. refreshWhenVisible in the view from step 5 reads the page again whenever a visitor comes back to the tab.

When you add a cache of your own, such as a CDN that keeps HTML or a step that prerenders pages, it needs a signed webhook to know when to clear it. The preview server already has the route, /api/cms-webhook. verifyWebhook checks the signature against the raw body and the webhook secret in constant time, refuses messages more than five minutes old and reads the event. The route answers 401 for a refused message and 204 otherwise. Replace the console.log with your purge, using result.data.url for the page that changed.

  1. Open Configuration › Webhooks and select New webhook. Address: https://northwilds.com/api/cms-webhook. Environment: Production.
  2. Copy the secret that starts with whsec_ into CMS_WEBHOOK_SECRET where the server runs, and restart it.
  3. In the webhook's ⋯ menu, select Send a test. The CMS shows that the website answered 204.

Next steps

Was this page helpful?

Read next