Skip to content

React quickstart (Vite and React Router)

A client-rendered React website that reads CMS Orbit pages in the browser with the public key, previews drafts through a small server that holds the secret key, and shows new content on the next visit.

Tutorial13 min read

In about 20 minutes you build a React website for Northwilds with Vite and React Router. Every page an editor publishes appears at its own address, each component is drawn by a React component of yours, and editors see their drafts in the live preview as they type.

The website runs in the browser, so it reads published content with the public cms_pk_ key, which is safe there. Drafts need the secret cms_sk_ key, which must never reach the browser: a small Node.js server of about 60 lines holds it and answers the preview's draft requests. The SDK refuses to create a client with a secret key in browser code.

Tested with: Vite 8.3, React 19.3, React Router 8.5, TypeScript 7.0, @bifrost-orbit-cms/sdk 0.12.0, Node.js 24.

Prefer to start from a working project? Use the starter: bifrost-orbit/cms-starter-react, 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.9 or later. The preview server in step 7 reads its settings with --env-file-if-exists, which Node.js has from 22.9.

Search engines and link previews see a client-rendered page only after its JavaScript has run. If that matters for your website, use the Next.js quickstart instead, which renders on the server.

1Create the project

Shell
npm create vite@latest northwilds-site -- --template react-ts --no-interactivecd northwilds-siterm src/App.tsx src/App.cssrm -r src/assets

2Install the SDK

Shell
npm install @bifrost-orbit-cms/sdk react-router

The browser uses the client and the React renderer. The preview server in step 7 uses the same client with the secret key.

3Add the settings

.env.localShell
VITE_CMS_API_URL=https://api.bifrostorbit.com/cmsVITE_CMS_PUBLIC_KEY=cms_pk_...VITE_CMS_REGION=globalCMS_API_URL=https://api.bifrostorbit.com/cmsCMS_PUBLIC_KEY=cms_pk_...CMS_PREVIEW_KEY=cms_sk_...CMS_DEFAULT_REGION=globalCMS_WEBHOOK_SECRET=
  • VITE_ settings are copied into the browser bundle by Vite. Only the public key may go there.
  • The others are read only by the type generator and the preview server. Vite never sends them to the browser. Never give the secret key or the webhook secret a VITE_ prefix.
  • Vite's .gitignore already keeps *.local files out of git.

Tell TypeScript about the browser settings:

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

4Create the client

src/lib/cms.tsTypeScript
import { createCmsClient } 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_REGION,})

In the browser, the client sends the public key in the address, so our CDN can answer repeated requests from its cache. Leave out the cache option: it only means something to Next.js.

5Show a page

Start with an empty registry. Step 6 fills it.

src/cms/registry.tsxTypeScript
import type { CmsRegistry } from '@bifrost-orbit-cms/sdk/react'export const registry: CmsRegistry = {}

A loader asks CMS Orbit what lives at the address before the page renders:

src/routes/load-page.tsTypeScript
import { data, redirect, type LoaderFunctionArgs } from 'react-router'import { cms } from '../lib/cms'export async function loadPage({ request }: LoaderFunctionArgs) {  const path = new URL(request.url).pathname.replace(/\/+$/, '') || '/'  const result = await cms.resolve({ path, signal: request.signal })  if (result.kind === 'redirect') throw redirect(result.to, result.status)  if (result.kind !== 'page') throw data(null, { status: 404 })  return result.page}
src/routes/cms-route.tsxTypeScript
import { CmsPage } from '@bifrost-orbit-cms/sdk/react'import { isRouteErrorResponse, Link, useLoaderData, useRouteError } from 'react-router'import { registry } from '../cms/registry'import type { loadPage } from './load-page'export function CmsRoute() {  const page = useLoaderData<typeof loadPage>()  return (    <main>      <title>{page.seo.title}</title>      <meta name="description" content={page.seo.description} />      <CmsPage page={page} registry={registry} />    </main>  )}export function CmsError() {  const error = useRouteError()  const notFound = isRouteErrorResponse(error) && error.status === 404  return (    <main>      <title>{notFound ? 'Page not found' : 'Something went wrong'}</title>      <h1>{notFound ? 'Page not found' : 'Something went wrong'}</h1>      <p>{notFound ? 'The page you were looking for is not here.' : 'Please try again in a moment.'}</p>      <Link to="/">Go to the home page</Link>    </main>  )}

Replace src/main.tsx with one route that matches every address:

src/main.tsxTypeScript
import { StrictMode } from 'react'import { createRoot } from 'react-dom/client'import { createBrowserRouter } from 'react-router'import { RouterProvider } from 'react-router/dom'import { CmsError, CmsRoute } from './routes/cms-route'import { loadPage } from './routes/load-page'import './index.css'const router = createBrowserRouter([  { path: '*', loader: loadPage, Component: CmsRoute, ErrorBoundary: CmsError, HydrateFallback: () => null },])createRoot(document.getElementById('root')!).render(  <StrictMode>    <RouterProvider router={router} />  </StrictMode>,)
  • *`path: ''** sends every address to the same route, and the loader passes it to cms.resolve` without a trailing slash, as CMS Orbit stores it.
  • cms.resolve answers page, redirect (when an editor moved the page or added a redirect), gone or notFound. Redirects happen in the browser. Unknown and removed addresses show the not found page.
  • <title> and <meta> inside a component are moved into <head> by React 19.
  • Static hosting answers 200 for every address, because it serves index.html for all of them. The visitor sees "Page not found", but the HTTP status is not 404. Only a server can send a real 404 or 301.

Check it: run npm run dev and open http://localhost:5173. The tab shows the page's title, and each component is a dashed box saying "No renderer registered for …" with its type. That box only appears in development; a production build renders nothing for an unknown component. Open /this-does-not-exist to see the not found page.

6Write and register components

Generate types for your space's components. Add a script to package.json:

JSON
{  "scripts": {    "cms:types": "cms-orbit generate --out src/cms/types.ts"  }}
Shell
npm run cms:types

It reads CMS_API_URL and CMS_PUBLIC_KEY from .env.local and prints something like Wrote 60 components and 10 content types to src/cms/types.ts.

Now draw a component. Open Configuration › Components to see your components and their fields, or read them in src/cms/types.ts. The Northwilds home page starts with a hero that holds two action buttons:

src/components/blocks/hero.tsxTypeScript
import { RichText, type BlockProps } from '@bifrost-orbit-cms/sdk/react'export function Hero({ block, slots }: BlockProps<'hero'>) {  return (    <section data-cms-id={block.id} className="hero">      {block.eyebrow ? <p className="eyebrow">{block.eyebrow}</p> : null}      <h1>        {block.heading} {block.headingAccent ? <span>{block.headingAccent}</span> : null}      </h1>      <RichText value={block.description} />      <div className="actions">        {slots.primaryAction}        {slots.secondaryAction}      </div>    </section>  )}
src/components/blocks/action.tsxTypeScript
import type { BlockProps } from '@bifrost-orbit-cms/sdk/react'export function Action({ block }: BlockProps<'action'>) {  if (!block.link?.href) return null  return (    <a data-cms-id={block.id} href={block.link.href} target={block.link.target ?? undefined} className={block.style}>      {block.label}    </a>  )}

A grid of features shows nested blocks: each featureItem inside a featureGrid is a component of its own.

src/components/blocks/feature-grid.tsxTypeScript
import type { BlockProps } from '@bifrost-orbit-cms/sdk/react'export function FeatureGrid({ block, slots }: BlockProps<'featureGrid'>) {  return (    <section data-cms-id={block.id} className="feature-grid">      <h2>{block.heading}</h2>      {block.intro ? <p>{block.intro}</p> : null}      <div className="grid">{slots.items}</div>    </section>  )}
src/components/blocks/feature-item.tsxTypeScript
import type { BlockProps } from '@bifrost-orbit-cms/sdk/react'export function FeatureItem({ block }: BlockProps<'featureItem'>) {  return (    <article data-cms-id={block.id}>      <h3>{block.title}</h3>      <p>{block.body}</p>    </article>  )}

Register them. Replace src/cms/registry.tsx:

src/cms/registry.tsxTypeScript
import './types'import type { CmsRegistry } from '@bifrost-orbit-cms/sdk/react'import { Action } from '../components/blocks/action'import { FeatureGrid } from '../components/blocks/feature-grid'import { FeatureItem } from '../components/blocks/feature-item'import { Hero } from '../components/blocks/hero'export const registry: CmsRegistry = {  hero: Hero,  action: Action,  featureGrid: FeatureGrid,  featureItem: FeatureItem,}
  • BlockProps<'hero'> types block with the hero's fields from the generated types. A misspelt field is a type error.
  • slots holds the nested blocks of each Component or Components field, already drawn with the registry.
  • data-cms-id={block.id} lets editors click the block in the preview to select it.
  • Your component keys will differ from these. Use the keys from your own space.
  • A typed CmsRegistry lets you add components one at a time. Once every component is drawn, switch to defineRegistry({ … }), which makes a missing component a type error. See Render components.

Check it: reload the page. The hero shows its heading and buttons.

7Preview drafts in the editor

The editor opens your page with a preview token, such as https://stage.northwilds.com/gear/fjell-gtx-boot?preview=eyJ…. The browser cannot read the draft itself, because that needs the secret key. Instead it sends the token to your own server, which checks it with CMS Orbit and reads the draft.

The server holds the secret key. It answers the draft requests now and the webhook in step 8:

server/index.mjsJavaScript
import { createServer } from 'node:http'import { createCmsClient, verifyWebhook } from '@bifrost-orbit-cms/sdk'const cms = createCmsClient({  baseUrl: process.env.CMS_API_URL,  apiKey: process.env.CMS_PUBLIC_KEY,  previewKey: process.env.CMS_PREVIEW_KEY,  defaultRegion: process.env.CMS_DEFAULT_REGION,})async function readBody(request) {  const chunks = []  for await (const chunk of request) chunks.push(chunk)  return Buffer.concat(chunks).toString('utf8')}function send(response, status, body) {  response.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' })  response.end(body === undefined ? undefined : JSON.stringify(body))}createServer(async (request, response) => {  const url = new URL(request.url, 'http://localhost')  try {    if (request.method === 'GET' && url.pathname === '/api/draft') {      const preview = await cms.checkPreview(request.headers['x-preview-token'])      if (!preview.valid) return send(response, 401, { error: 'invalid_token' })      const path = url.searchParams.get('path') || '/'      return send(response, 200, await cms.resolve({ path, preview: true }))    }    if (request.method === 'POST' && url.pathname === '/api/cms-webhook') {      const secret = process.env.CMS_WEBHOOK_SECRET      if (!secret) return send(response, 401)      const result = await verifyWebhook({        body: await readBody(request),        timestamp: request.headers['x-orbit-timestamp'],        signature: request.headers['x-orbit-signature'],        secret,      })      if (!result.valid) return send(response, 401)      console.log('CMS Orbit published', result.event, result.data.url ?? '')      return send(response, 204)    }    send(response, 404, { error: 'not_found' })  } catch (error) {    console.error(error)    send(response, 502, { error: 'cms_unavailable' })  }}).listen(Number(process.env.PORT ?? 8787))
  • /api/draft answers 401 for a missing, invalid or expired token, which cms.checkPreview checks with CMS Orbit. Tokens last an hour, and the editor makes new ones as needed. For a valid token it answers with the draft, read with the secret key.
  • The secret key never leaves this server. Anyone without a valid token from the editor gets nothing.

Add a script to start it, and let Vite's development server pass /api on to it:

JSON
{  "scripts": {    "server": "node --env-file-if-exists=.env.local server/index.mjs"  }}

--env-file-if-exists reads .env.local 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.

vite.config.tsTypeScript
import react from '@vitejs/plugin-react'import { defineConfig } from 'vite'export default defineConfig({  plugins: [react()],  server: { proxy: { '/api': 'http://localhost:8787' } },})

The browser remembers the token for the tab and asks the server for drafts while it has one:

src/lib/preview.tsTypeScript
const STORAGE_KEY = 'cms-preview-token'export function previewToken(request: Request): string | null {  const token = new URL(request.url).searchParams.get('preview')  if (token) sessionStorage.setItem(STORAGE_KEY, token)  return sessionStorage.getItem(STORAGE_KEY)}export function endPreview() {  sessionStorage.removeItem(STORAGE_KEY)}

Replace src/routes/load-page.ts:

src/routes/load-page.tsTypeScript
import type { CmsResolution } from '@bifrost-orbit-cms/sdk'import { data, redirect, type LoaderFunctionArgs } from 'react-router'import { cms } from '../lib/cms'import { endPreview, previewToken } from '../lib/preview'async function readDraft(path: string, token: string, signal: AbortSignal): Promise<CmsResolution | null> {  const response = await fetch(`/api/draft?path=${encodeURIComponent(path)}`, { headers: { 'x-preview-token': token }, signal })  if (response.status === 401) {    endPreview()    return null  }  if (!response.ok) throw new Error(`The preview server answered ${response.status}`)  return response.json()}export async function loadPage({ request }: LoaderFunctionArgs) {  const path = new URL(request.url).pathname.replace(/\/+$/, '') || '/'  const token = previewToken(request)  const result = (token && (await readDraft(path, token, request.signal))) || (await cms.resolve({ path, signal: request.signal }))  if (result.kind === 'redirect') throw redirect(result.to, result.status)  if (result.kind !== 'page') throw data(null, { status: 404 })  return result.page}

An expired token ends the preview and the published page is shown instead. Visitors without a token never call the server.

The page shows the draft with CmsLivePage and loads the bridge. Replace CmsRoute in src/routes/cms-route.tsx; CmsError stays as it is:

src/routes/cms-route.tsxTypeScript
import { CmsLivePage, CmsPage } from '@bifrost-orbit-cms/sdk/react'import { isRouteErrorResponse, Link, useLoaderData, useRouteError } from 'react-router'import { registry } from '../cms/registry'import { cms } from '../lib/cms'import type { loadPage } from './load-page'export function CmsRoute() {  const page = useLoaderData<typeof loadPage>()  return (    <main>      <title>{page.seo.title}</title>      <meta name="description" content={page.seo.description} />      {page.draft ? (        <>          <CmsLivePage page={page} registry={registry} />          <script async src={`${cms.origin}/bridge.js`} />        </>      ) : (        <CmsPage page={page} registry={registry} />      )}    </main>  )}
  • page.draft is true only for pages the server read with the secret key.
  • CmsLivePage listens to the editor through the bridge and redraws the page as editors type, without reloading.
  • The bridge script must be async. React 19 loads an async script rendered in a component, but never runs other scripts it renders in the browser. For the same reason, use this line rather than CmsBridge from the SDK, which renders a defer script for server rendering.

Tell the CMS where the website is: in the space's Settings, set Preview URL to the address of the website, such as https://stage.northwilds.com.

Check it: run npm run server in one terminal and npm run dev in another. Open a page in the editor, change a heading without publishing, and watch the preview change. Click a block to select it in the editor. The website must allow CMS Orbit to show it in a frame; see Set up the live preview.

When you deploy, build with npm run build and serve dist as static files, with every address falling back to index.html. Run server/index.mjs with the same settings, and send /api/ on the website's own domain to it, for example with your host's rewrites or a reverse proxy. Keeping both on one domain means the browser needs no CORS settings.

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. To read the page again when a visitor comes back to the tab, add this to CmsRoute:

src/routes/cms-route.tsx, in CmsRouteTypeScript
import { useEffect } from 'react'import { useRevalidator } from 'react-router'const { revalidate } = useRevalidator()useEffect(() => {  const refresh = () => document.visibilityState === 'visible' && revalidate()  document.addEventListener('visibilitychange', refresh)  return () => document.removeEventListener('visibilitychange', refresh)}, [revalidate])

revalidate runs the loader again and redraws the page with the latest content.

When you add a cache of your own, such as a CDN that keeps HTML or a server that prerenders pages, it needs a signed webhook to know when to clear it. The server from step 7 already has the route, /api/cms-webhook. verifyWebhook checks the x-orbit-signature header against your secret in constant time and refuses messages more than five minutes old, so the route answers 401 for those 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