Skip to content

Astro quickstart

An Astro website rendered on the server that shows every CMS Orbit page at its own address, previews drafts in the editor and clears its page cache when editors publish.

Tutorial11 min read

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

The website renders on the server with the Node.js adapter, so new pages appear without a rebuild. It uses the SDK's core client only: React is not needed.

Tested with: Astro 7.4.7, @astrojs/node 11.1.11, @bifrost-orbit-cms/sdk 0.12.0, Node.js 24.

Prefer to start from a working project? Use the starter: bifrost-orbit/cms-starter-astro, 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 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.23 or later, which Astro 7 needs.

1Create the project

Shell
npm create astro@latest northwilds-site -- --template withastro/astro/examples/minimal --install --no-git --yescd northwilds-sitenpx astro add node --yesrm src/pages/index.astro

astro add node installs the Node.js adapter, so pages render on each request. src/pages/index.astro is removed because the page route in step 5 also answers /.

2Install the SDK

Shell
npm install @bifrost-orbit-cms/sdk

3Add the settings

.envShell
CMS_API_URL=https://api.bifrostorbit.com/cmsCMS_PUBLIC_KEY=cms_pk_...CMS_PREVIEW_KEY=cms_sk_...CMS_DEFAULT_REGION=globalCMS_WEBHOOK_SECRET=

Use your own region key. CMS_WEBHOOK_SECRET stays empty until step 8. Astro keeps .env out of git.

Declare the settings in astro.config.mjs, so Astro checks them when the server starts and keeps the secret ones out of browser code. The same file turns on server rendering and Astro's page cache:

astro.config.mjsJavaScript
import { defineConfig, envField, memoryCache } from 'astro/config'import node from '@astrojs/node'export default defineConfig({  output: 'server',  adapter: node({ mode: 'standalone' }),  cache: { provider: memoryCache() },  env: {    schema: {      CMS_API_URL: envField.string({ context: 'server', access: 'public' }),      CMS_PUBLIC_KEY: envField.string({ context: 'server', access: 'secret' }),      CMS_PREVIEW_KEY: envField.string({ context: 'server', access: 'secret', optional: true }),      CMS_WEBHOOK_SECRET: envField.string({ context: 'server', access: 'secret', optional: true }),      CMS_DEFAULT_REGION: envField.string({ context: 'server', access: 'public', default: 'global' }),    },  },})

memoryCache() keeps rendered pages in the server's memory. Astro skips the cache while you run astro dev, so you see changes at once.

4Create the client

src/lib/cms.tsTypeScript
import { createCmsClient } from '@bifrost-orbit-cms/sdk'import { CMS_API_URL, CMS_DEFAULT_REGION, CMS_PREVIEW_KEY, CMS_PUBLIC_KEY } from 'astro:env/server'export const cms = createCmsClient({  baseUrl: CMS_API_URL,  apiKey: CMS_PUBLIC_KEY,  previewKey: CMS_PREVIEW_KEY,  defaultRegion: CMS_DEFAULT_REGION,})export async function isPreview(url: URL): Promise<boolean> {  if (!CMS_PREVIEW_KEY) return false  const check = await cms.checkPreview(url.searchParams.get('preview'))  return check.valid}

astro:env/server can only be imported in server code, so the secret key cannot end up in a browser bundle. isPreview is used in step 7.

5Show a page

One catch-all route answers every address and asks CMS Orbit what is there:

Astro
---// src/pages/[...slug].astroimport { cacheTags } from '@bifrost-orbit-cms/sdk'import Layout from '../layouts/Layout.astro'import Block from '../components/Block.astro'import { cms, isPreview } from '../lib/cms'const path = '/' + (Astro.params.slug ?? '')const preview = await isPreview(Astro.url)const result = await cms.resolve({ path, preview })if (result.kind === 'redirect') return Astro.redirect(result.to, result.status as 301 | 302 | 307 | 308)if (result.kind === 'gone') return new Response(null, { status: 410 })if (result.kind === 'notFound') return new Response(null, { status: 404 })const page = result.pageif (!preview) {  Astro.cache.set({ maxAge: 60, swr: 60, tags: [cacheTags.all, cacheTags.page(page.region, path)] })}---<Layout title={page.seo.title} description={page.seo.description} lang={page.locale} preview={preview}>  <main>    {page.components.map((block) => <Block block={block} />)}  </main></Layout>
  • resolve answers with the page, a redirect (such as a page whose address changed), gone for a deleted page or notFound.
  • A 404 with no body makes Astro show src/pages/404.astro with the right status.
  • Astro.cache.set keeps the published page for 60 seconds, and for another 60 while a fresh copy is rendered. The tags let the webhook in step 8 clear only this page. Drafts are never cached.

The layout sets the title, description and language from the page:

Astro
---// src/layouts/Layout.astroimport { cms } from '../lib/cms'interface Props {  title: string  description?: string  lang?: string  preview?: boolean}const { title, description, lang = 'en', preview = false } = Astro.props---<!doctype html><html lang={lang}>  <head>    <meta charset="utf-8" />    <meta name="viewport" content="width=device-width, initial-scale=1" />    <title>{title}</title>    {description && <meta name="description" content={description} />}    {preview && <script is:inline src={`${cms.origin}/bridge.js`} defer></script>}  </head>  <body>    <slot />  </body></html>
Astro
---// src/pages/404.astroimport Layout from '../layouts/Layout.astro'---<Layout title="Page not found · Northwilds">  <main>    <h1>We couldn't find that page</h1>    <p><a href="/">Back to the home page</a></p>  </main></Layout>

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.

6Write and register components

Generate types for your space's components, so each component knows its fields. 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 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. Block finds the component for each block's type, and shows a note for types you have not written yet while you develop:

Astro
---// src/components/Block.astroimport type { CmsComponent } from '@bifrost-orbit-cms/sdk'import { registry } from './registry'interface Props {  block: CmsComponent}const { block } = Astro.propsconst Component = registry[block.type]---{Component ? <Component block={block} /> : import.meta.env.DEV && <p data-cms-id={block.id}>No component for <code>{block.type}</code> yet.</p>}

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/components/registry.tsTypeScript
import Action from './Action.astro'import FeatureSpotlight from './FeatureSpotlight.astro'import Hero from './Hero.astro'export const registry: Record<string, (props: { block: any }) => unknown> = {  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 set: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 Block too:

Astro
---// src/components/Hero.astroimport type { CmsNode } from '@bifrost-orbit-cms/sdk'import type { HeroBlock } from '../cms/types'import Block from './Block.astro'interface Props {  block: CmsNode<HeroBlock>}const { block } = Astro.propsconst { eyebrow, heading, description, primaryAction, secondaryAction } = block.fields---<section data-cms-id={block.id} class="hero">  {eyebrow && <p class="eyebrow">{eyebrow}</p>}  <h1>{heading}</h1>  {description && <div set:html={description} />}  <div class="actions">    {primaryAction && <Block block={primaryAction} />}    {secondaryAction && <Block block={secondaryAction} />}  </div></section>

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

Astro
---// src/components/FeatureSpotlight.astroimport { cmsImageSrcSet, type CmsNode } from '@bifrost-orbit-cms/sdk'import type { FeatureSpotlightBlock } from '../cms/types'import Block from './Block.astro'interface Props {  block: CmsNode<FeatureSpotlightBlock>}const { block } = Astro.propsconst { eyebrow, heading, body, image, action } = block.fields---<section data-cms-id={block.id} class="spotlight">  {eyebrow && <p class="eyebrow">{eyebrow}</p>}  <h2>{heading}</h2>  {body && <div set:html={body} />}  {image && (    <img      src={image.url}      srcset={cmsImageSrcSet(image.url, image.width)}      sizes="(min-width: 768px) 50vw, 100vw"      width={image.width ?? undefined}      height={image.height ?? undefined}      alt={image.alt}      loading="lazy"    />  )}  {action && <Block block={action} />}</section>

The button itself. A link to a page carries the page's current address in href, and null when that page is not published:

Astro
---// src/components/Action.astroimport type { CmsNode } from '@bifrost-orbit-cms/sdk'import type { ActionBlock } from '../cms/types'interface Props {  block: CmsNode<ActionBlock>}const { block } = Astro.propsconst { label, link, style = 'primary' } = block.fields---{link?.href ? (  <a data-cms-id={block.id} class={`button ${style}`} href={link.href} target={link.target ?? undefined}>{label}</a>) : (  <span data-cms-id={block.id} class={`button ${style}`}>{label}</span>)}

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:4321/ 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 page.

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….

Step 4 and step 5 already handle it:

  1. isPreview checks the token with CMS Orbit through cms.checkPreview.
  2. The page then reads the draft with preview: true, which sends the secret key and asks for drafts.
  3. The layout adds the bridge script, so editors can click a block to select it, and the preview reloads after each save.
  4. 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. Draft pages skip Astro.cache.set, so they are never cached and never shown to visitors. Each token lasts an hour, and the editor makes new ones as needed.

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:

Shell
npm run buildnode --env-file=.env dist/server/entry.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. 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.

8Refresh when editors publish

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

src/pages/api/cms-webhook.tsTypeScript
import type { APIRoute } from 'astro'import { cacheTags, verifyWebhook } from '@bifrost-orbit-cms/sdk'import { CMS_WEBHOOK_SECRET } from 'astro:env/server'export const POST: APIRoute = async ({ request, cache }) => {  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 })  if (result.event === 'webhook.test') return new Response(null, { status: 204 })  const pageTag = result.tags.find((tag) => tag.startsWith('cms:page:'))  await cache.invalidate({ tags: pageTag ?? cacheTags.all })  return new Response(null, { status: 204 })}
  • verifyWebhook checks the signature, the HMAC-SHA256 of the timestamp, a full stop and the raw body keyed with the webhook secret, in constant time, and refuses messages more than five minutes old. It also reads the message and lists the cache tags it affects in result.tags.
  • A published, unpublished or deleted page comes with that page's tag, so only that page is cleared. A page that moved, a shared section, a menu or anything else clears every page, since any page may show it.
  • Region keys match because the page was tagged with page.region, the region's key, which is also what the webhook sends.

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 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.

memoryCache() lives in one server process. If you run several copies of the website, each keeps its own cache and a webhook reaches only one of them: use a cache provider that they share, or a CDN with its own purge, and clear it in the same place.

Next steps

Was this page helpful?

Read next