# Next.js quickstart

> A Next.js App Router website that renders every CMS Orbit page at its own address, previews drafts in the editor and refreshes when editors publish.

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

In about 15 minutes you build a Next.js 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 React component of yours, editors see their drafts in the live preview as they type, and publishing refreshes the page straight away.

This quickstart takes the shortest path. [Connect a website to CMS Orbit](https://docs.bifrostorbit.com/cms/developers/connect-a-website/) builds the same website with every option explained, plus menus, the footer, sitemaps and robots.txt.

**Tested with:** Next.js 16.4.5, React 19.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-nextjs](https://github.com/bifrost-orbit/cms-starter-nextjs), 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 create-next-app@latest northwilds-site --ts --app --eslint --no-tailwind --no-src-dir --import-alias "@/*" --no-cache-components --yes
cd northwilds-site
rm app/page.tsx app/page.module.css
```

- `--no-cache-components` matters. New Next.js 16 apps turn on Cache Components by default, and with it the page's `revalidate` setting in step 5 fails the build. This quickstart uses the SDK's own caching, which works without it.
- `app/page.tsx` is removed because the page route in step 5 also answers `/`.

## 2. Install the SDK

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

`server-only` makes the build fail if the file holding your secret key is ever imported into browser code.

## 3. Add the settings

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

Use your own region key. `CMS_WEBHOOK_SECRET` stays empty until step 8. Next.js keeps `.env.local` out of git. Never give these settings a `NEXT_PUBLIC_` prefix, which would copy them into the browser.

## 4. Create the client

```ts
// lib/cms.ts
import 'server-only'
import { createCmsClient } from '@bifrost-orbit-cms/sdk'

export const cms = createCmsClient({
  baseUrl: process.env.CMS_API_URL!,
  apiKey: process.env.CMS_PUBLIC_KEY!,
  previewKey: process.env.CMS_PREVIEW_KEY || undefined,
  defaultRegion: process.env.CMS_DEFAULT_REGION,
  cache: { revalidate: 60, tags: true },
})
```

`cache` keeps each answer for up to 60 seconds and labels it with cache tags, so the webhook in step 8 can refresh exactly the page that changed. Previews are never cached.

## 5. Show a page

Start with an empty registry. Step 6 fills it.

```tsx
// cms/registry.tsx
import type { CmsRegistry } from '@bifrost-orbit-cms/sdk/react'

export const registry: CmsRegistry = {}
```

One route renders every page in the CMS, whatever its address:

```tsx
// app/[[...slug]]/page.tsx
import type { Metadata } from 'next'
import { draftMode } from 'next/headers'
import { notFound, permanentRedirect, redirect } from 'next/navigation'
import { cache } from 'react'
import { gone } from '@bifrost-orbit-cms/sdk/next'
import { CmsPage } from '@bifrost-orbit-cms/sdk/react'
import { toMetadata } from '@bifrost-orbit-cms/sdk/seo'

import { registry } from '@/cms/registry'
import { cms } from '@/lib/cms'

type Props = { params: Promise<{ slug?: string[] }> }

export const revalidate = 60

export function generateStaticParams() {
  return []
}

const load = cache(async (path: string, preview: boolean) => cms.resolve({ path, preview }))

async function resolveFor({ params }: Props) {
  const { slug = [] } = await params
  const { isEnabled } = await draftMode()
  return load(`/${slug.join('/')}`, isEnabled)
}

export async function generateMetadata(props: Props): Promise<Metadata> {
  const result = await resolveFor(props)
  return result.kind === 'page' ? toMetadata(result.page) : {}
}

export default async function Page(props: Props) {
  const result = await resolveFor(props)

  if (result.kind === 'redirect') {
    if (result.permanent) permanentRedirect(result.to)
    redirect(result.to)
  }
  if (result.kind === 'gone') gone()
  if (result.kind === 'notFound') notFound()

  return (
    <main>
      <CmsPage page={result.page} registry={registry} />
    </main>
  )
}
```

```tsx
// app/not-found.tsx
import Link from 'next/link'

export default function NotFound() {
  return (
    <main>
      <h1>Page not found</h1>
      <p>The page you were looking for is not here.</p>
      <Link href="/">Go to the home page</Link>
    </main>
  )
}
```

- **`[[...slug]]`** matches every address, including `/`. `/gear/fjell-gtx-boot` arrives as `['gear', 'fjell-gtx-boot']`.
- **`cms.resolve`** answers `page`, `redirect` (when an editor moved the page or added a redirect), `gone` or `notFound`. Unknown and removed addresses show the 404 page.
- **`toMetadata`** sets the title, description, canonical address and share tags from the page's SEO fields.
- **`generateStaticParams` returning `[]`** builds no pages ahead of time, so the build does not need the CMS, but keeps each page after its first visit.

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

## 6. Write and register components

Generate types for your space's components, so each React component knows its fields. Add a script to `package.json`:

```json
{
  "scripts": {
    "cms:types": "cms-orbit generate --out cms/types.ts"
  }
}
```

```bash
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 cms/types.ts`.

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

```tsx
// components/blocks/hero.tsx
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>
  )
}
```

```tsx
// components/blocks/action.tsx
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.

```tsx
// components/blocks/feature-grid.tsx
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>
  )
}
```

```tsx
// components/blocks/feature-item.tsx
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 `cms/registry.tsx`:

```tsx
// cms/registry.tsx
import '@/cms/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 `cms/types.ts`. A misspelt field is a type error.
- **`slots`** holds the nested blocks of each Component or Components field, already drawn with the registry. `slots.items` is the grid's features.
- **`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](https://docs.bifrostorbit.com/cms/developers/render-blocks/).

**Check it:** reload `http://localhost:3000`. The hero shows its heading and buttons; the components you have not drawn yet still show the dashed box.

## 7. Preview 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…`. Five small files turn that into a draft view.

**The proxy** sends any address with `?preview=` to the preview route:

```ts
// proxy.ts
import { NextResponse, type NextRequest } from 'next/server'

export function proxy(request: NextRequest) {
  const token = request.nextUrl.searchParams.get('preview')
  if (!token) return NextResponse.next()
  const target = new URL('/api/preview', request.url)
  target.searchParams.set('preview', token)
  target.searchParams.set('path', request.nextUrl.pathname)
  return NextResponse.redirect(target)
}

export const config = {
  matcher: [{ source: '/((?!api/|_next/).*)', has: [{ type: 'query', key: 'preview' }] }],
}
```

`proxy.ts` sits next to `app`. It is what Next.js 15 called `middleware.ts`.

**The preview routes** check the token with CMS Orbit, turn draft mode on, and off again:

```ts
// app/api/preview/route.ts
import { createPreviewHandler } from '@bifrost-orbit-cms/sdk/next'
import { cms } from '@/lib/cms'

export const GET = createPreviewHandler({ client: cms })
```

```ts
// app/api/preview/exit/route.ts
import { createPreviewExitHandler } from '@bifrost-orbit-cms/sdk/next'

export const GET = createPreviewExitHandler()
```

A missing token answers `400` and an invalid or expired one `401`. A valid token turns on draft mode and redirects to the page. While draft mode is on, the page route from step 5 reads the draft with the secret key, uncached.

**The page body** redraws the draft as editors type:

```tsx
// components/live-page.tsx
'use client'

import type { CmsPage as CmsPageData } from '@bifrost-orbit-cms/sdk'
import { CmsLivePage } from '@bifrost-orbit-cms/sdk/react'

import { registry } from '@/cms/registry'

export function LivePage({ page }: { page: CmsPageData }) {
  return <CmsLivePage page={page} registry={registry} />
}
```

```tsx
// components/page-body.tsx
import type { CmsPage as CmsPageData } from '@bifrost-orbit-cms/sdk'
import { CmsPage } from '@bifrost-orbit-cms/sdk/react'

import { registry } from '@/cms/registry'

import { LivePage } from './live-page'

export function PageBody({ page }: { page: CmsPageData }) {
  if (page.draft) return <LivePage page={page} />
  return <CmsPage page={page} registry={registry} />
}
```

In `app/[[...slug]]/page.tsx`, import `PageBody` from `@/components/page-body` and render `<PageBody page={result.page} />` in place of `<CmsPage … />`. Published pages still render on the server.

**The bridge** connects the preview to the editor. Replace `app/layout.tsx`:

```tsx
// app/layout.tsx
import type { ReactNode } from 'react'
import { CmsBridge } from '@bifrost-orbit-cms/sdk/next'

import { cms } from '@/lib/cms'

import './globals.css'

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <CmsBridge client={cms} />
      </body>
    </html>
  )
}
```

`CmsBridge` adds the bridge script only while draft mode is on, so visitors never load it.

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

**Check it:** open a page in the editor, change a heading without publishing, and watch the preview change. With `npm run dev`, Next.js only keeps the draft mode cookie in the website's own tab, so use **Open in a new tab** above the preview, or run `npm run build` and `npm start`. The website must allow CMS Orbit to show it in a frame; see [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. With it, it appears straight away.

```ts
// app/api/revalidate/route.ts
import { createRevalidateHandler } from '@bifrost-orbit-cms/sdk/next'

export async function POST(request: Request): Promise<Response> {
  const secret = process.env.CMS_WEBHOOK_SECRET
  if (!secret) return Response.json({ error: { code: 'not_configured' } }, { status: 503 })
  return createRevalidateHandler({ secret })(request)
}
```

The handler checks the `x-orbit-signature` header against your secret, refuses messages with a bad signature or older than five minutes with `401`, and refreshes the cache tags of what changed.

1. Deploy the website, so the route has a public `https` address.
2. Open **Configuration › Webhooks** and select **New webhook**. **Address:** `https://northwilds.com/api/revalidate`. **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 redeploy.

**Check it:** in the webhook's **⋯** menu, select **Send a test**. The answer is `{"revalidated":[]}`. Then publish a change and reload the page: **Deliveries** shows the tags that were refreshed, such as `["cms:page:global:/pricing","cms:list","cms:sitemap","cms:references"]`.

## Next steps

- [Connect a website to CMS Orbit](https://docs.bifrostorbit.com/cms/developers/connect-a-website/): the full tutorial, with menus, the footer, structured data, sitemaps and robots.txt.
- [Render components](https://docs.bifrostorbit.com/cms/developers/render-blocks/): images, links, variants, shared sections and `defineRegistry`.
- [Set up the live preview](https://docs.bifrostorbit.com/cms/developers/preview/): marking the header and footer, `useLivePage` and accessibility checks.
- [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 on one domain.
- [Metadata, sitemaps and robots](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/).
