# Angular quickstart

> An Angular website with server-side rendering that renders every CMS Orbit page at its own address with standalone components, previews drafts in the editor and refreshes when editors publish.

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

In about 20 minutes you build an Angular 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 standalone Angular component of yours, editors see their drafts in the live preview, and publishing refreshes the page straight away.

The SDK's client, `@bifrost-orbit-cms/sdk`, runs only on the server, in the Express server that Angular's server-side rendering creates. The server reads the page and hands it to Angular, which renders it and passes it to the browser for hydration. Your keys never reach the browser.

**Tested with:** Angular 22.2 with `@angular/ssr` 22.2, Express 5.3, `@bifrost-orbit-cms/sdk` 0.12.0, TypeScript 6.0, Node.js 24.

Prefer to start from a working project? Use the starter: [bifrost-orbit/cms-starter-angular](https://github.com/bifrost-orbit/cms-starter-angular), 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.9 or later**, for `--env-file` and `--env-file-if-exists` (the production server starts without a `.env` file when the settings are already in the environment).

## 1. Create the project

```bash
npx @angular/cli@latest new northwilds-site --ssr --defaults
cd northwilds-site
```

`--ssr` adds the Express server in `src/server.ts` and the server configuration. The welcome page in `src/app` is replaced in step 5.

## 2. Install the SDK

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

## 3. Add the settings

Create `.env` in the root of the project:

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

Keep it out of Git, since the new project's `.gitignore` does not:

```bash
echo ".env" >> .gitignore
```

Angular does not read `.env` by itself, so let Node load it. In `package.json`, change two scripts:

```json
"start": "node --env-file=.env node_modules/@angular/cli/bin/ng.js serve",
"serve:ssr:northwilds-site": "node --env-file-if-exists=.env dist/northwilds-site/server/server.mjs"
```

Angular's server only renders for host names it knows, to prevent server-side request forgery. In `angular.json`, under `projects › northwilds-site › architect › build › options`, list your website's:

```json
"security": {
  "allowedHosts": ["localhost", "northwilds.com", "stage.northwilds.com"]
}
```

Any other host name gets `400 Bad Request`. You can also set them in `NG_ALLOWED_HOSTS` where the website runs.

## 4. Create the client

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

let client: CmsClient | undefined

export function cms(): CmsClient {
  client ??= 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'],
  })
  return client
}

const MAX_AGE_MS = 60_000
const pages = new Map<string, { at: number; result: Promise<CmsResolution> }>()

export function resolvePage(path: string, preview: boolean): Promise<CmsResolution> {
  if (preview) return cms().resolve({ path, preview: true })
  const cached = pages.get(path)
  if (cached && Date.now() - cached.at < MAX_AGE_MS) return cached.result
  const result = cms().resolve({ path })
  pages.set(path, { at: Date.now(), result })
  result.catch(() => pages.delete(path))
  return result
}

export function purge(path?: string) {
  if (path) pages.delete(path)
  else pages.clear()
}

export const PREVIEW_COOKIE = 'cms_preview'

export function safePath(path: unknown): string {
  return typeof path === 'string' && path.startsWith('/') && !path.startsWith('//') && !path.includes('\\') ? path : '/'
}
```

- The file sits next to `server.ts`, outside `src/app`, and only `server.ts` imports it. Nothing in the browser build can reach it.
- `cms()` creates the client on first use. `ng build` loads the server to find its routes, and the keys are not there at build time.
- Angular has no data cache for this, so `resolvePage` keeps published pages in memory for 60 seconds. Drafts are never cached. `purge` is what the webhook in step 8 calls. On several servers, keep the answers in a shared cache, such as Redis, instead.
- `safePath` keeps the preview's redirects in step 7 on your own website.

## 5. Show a page

The server reads the page for each address and passes the result to Angular as the request context. Angular puts it in the transfer state, so the browser hydrates the same page without asking again.

The shape of that context, shared by the server and the app:

```ts
// src/app/cms/page-context.ts
import { makeStateKey } from '@angular/core'
import type { CmsResolution } from '@bifrost-orbit-cms/sdk'

export type CmsPageContext = {
  result: CmsResolution
  preview: boolean
  bridge: string
}

export const CMS_PAGE = makeStateKey<CmsPageContext>('cms-page')
```

Replace `src/server.ts`. It holds the page route, plus the preview and webhook routes explained in steps 7 and 8:

```ts
// src/server.ts
import { AngularNodeAppEngine, createNodeRequestHandler, isMainModule, writeResponseToNodeResponse } from '@angular/ssr/node'
import { verifyWebhook } from '@bifrost-orbit-cms/sdk'
import express, { type Request } from 'express'
import { join } from 'node:path'
import type { CmsPageContext } from './app/cms/page-context'
import { cms, PREVIEW_COOKIE, purge, resolvePage, safePath } from './cms.server'

const browserDistFolder = join(import.meta.dirname, '../browser')
const app = express()
const angularApp = new AngularNodeAppEngine()
const cookieOptions = { path: '/', httpOnly: true, secure: true, sameSite: 'none' } as const

function previewCookie(req: Request): string | undefined {
  const match = req.headers.cookie?.match(new RegExp(`(?:^|;\\s*)${PREVIEW_COOKIE}=([^;]+)`))
  return match ? decodeURIComponent(match[1]) : undefined
}

app.get('/api/preview', async (req, res) => {
  const token = req.query['preview'] ?? req.query['token']
  if (typeof token !== 'string' || !token) return void res.status(400).send('A preview token is required')
  const check = await cms().checkPreview(token)
  if (!check.valid) return void res.status(401).send('That preview link is invalid or has expired')
  res.cookie(PREVIEW_COOKIE, token, { ...cookieOptions, maxAge: 60 * 60 * 1000 })
  res.redirect(307, check.path ?? safePath(req.query['path']))
})

app.get('/api/preview/exit', (req, res) => {
  res.clearCookie(PREVIEW_COOKIE, cookieOptions)
  res.redirect(307, safePath(req.query['path']))
})

app.post('/api/cms-webhook', express.text({ type: '*/*' }), async (req, res) => {
  const secret = process.env['CMS_WEBHOOK_SECRET']
  if (!secret) return void res.sendStatus(401)
  const result = await verifyWebhook({
    body: typeof req.body === 'string' ? req.body : '',
    timestamp: req.get('x-orbit-timestamp'),
    signature: req.get('x-orbit-signature'),
    secret,
  })
  if (!result.valid) return void res.sendStatus(401)

  const { event } = result
  const data = result.data as { url?: string; previousUrl?: string }
  if (event === 'webhook.test') return void res.sendStatus(204)
  const moved = data.previousUrl && data.previousUrl !== data.url
  if (event.startsWith('content.') && data.url && !moved) purge(data.url)
  else purge()
  res.sendStatus(204)
})

app.use(express.static(browserDistFolder, { maxAge: '1y', index: false, redirect: false }))

app.get('/{*path}', async (req, res, next) => {
  try {
    const token = typeof req.query['preview'] === 'string' ? req.query['preview'] : null
    if (token) return res.redirect(307, `/api/preview?${new URLSearchParams({ preview: token, path: req.path })}`)

    const { valid: preview } = await cms().checkPreview(previewCookie(req))
    const result = await resolvePage(req.path, preview)
    if (result.kind === 'redirect') return res.redirect(result.status, result.to)

    const context: CmsPageContext = { result, preview, bridge: `${cms().origin}/bridge.js` }
    const response = await angularApp.handle(req, context)
    return response ? writeResponseToNodeResponse(response, res) : next()
  } catch (error) {
    next(error)
  }
})

if (isMainModule(import.meta.url) || process.env['pm_id']) {
  const port = process.env['PORT'] || 4000
  app.listen(port, (error) => {
    if (error) throw error
    console.log(`Node Express server listening on http://localhost:${port}`)
  })
}

export const reqHandler = createNodeRequestHandler(app)
```

`resolve` answers with the page, or with what to do instead. The server sends redirects itself, with their own status (such as 308 for a page that moved). For `gone` and `notFound`, Angular renders a not-found page with status 410 or 404.

One route draws every address:

```ts
// src/app/app.routes.ts
import { Routes } from '@angular/router'
import { CmsPage } from './cms/cms-page'

export const routes: Routes = [{ path: '**', component: CmsPage }]
```

Render every page on the server for each request, instead of prerendering at build time:

```ts
// src/app/app.routes.server.ts
import { RenderMode, ServerRoute } from '@angular/ssr'

export const serverRoutes: ServerRoute[] = [{ path: '**', renderMode: RenderMode.Server }]
```

The root component only holds the router outlet. Delete `src/app/app.css`, which it no longer uses:

```ts
// src/app/app.ts
import { Component } from '@angular/core'
import { RouterOutlet } from '@angular/router'

@Component({
  selector: 'app-root',
  imports: [RouterOutlet],
  templateUrl: './app.html',
})
export class App {}
```

```html
<!-- src/app/app.html -->
<router-outlet />
```

The page component reads the context on the server, stores it in the transfer state, sets the status, title, description and canonical address, and draws the components. In the browser, it reads the same page from the transfer state:

```ts
// src/app/cms/cms-page.ts
import { Component, DOCUMENT, inject, REQUEST_CONTEXT, RESPONSE_INIT, TransferState } from '@angular/core'
import { Meta, Title } from '@angular/platform-browser'
import type { CmsPage as CmsPageData } from '@bifrost-orbit-cms/sdk'
import { Blocks } from '../blocks/blocks'
import { CMS_PAGE, type CmsPageContext } from './page-context'

@Component({
  selector: 'cms-page',
  imports: [Blocks],
  template: `
    @if (page; as page) {
      <main><cms-blocks [blocks]="page.components" /></main>
    } @else {
      <main>
        <h1>{{ gone ? 'This page has been removed' : 'We could not find that page' }}</h1>
        <p><a href="/">Back to the home page</a></p>
      </main>
    }
  `,
})
export class CmsPage {
  protected readonly page: CmsPageData | null
  protected readonly gone: boolean

  constructor() {
    const state = inject(TransferState)
    const server = inject(REQUEST_CONTEXT, { optional: true }) as CmsPageContext | null
    if (server) state.set(CMS_PAGE, server)
    const context = server ?? state.get(CMS_PAGE, null)
    const result = context?.result

    this.page = result?.kind === 'page' ? result.page : null
    this.gone = result?.kind === 'gone'

    const response = inject(RESPONSE_INIT, { optional: true })
    if (response && !this.page) response.status = this.gone ? 410 : 404

    if (server) this.writeHead(server)
  }

  private writeHead(context: CmsPageContext) {
    const document = inject(DOCUMENT)
    inject(Title).setTitle(this.page?.seo.title ?? 'Page not found | Northwilds')
    if (!this.page) return
    inject(Meta).updateTag({ name: 'description', content: this.page.seo.description })

    const canonical = document.createElement('link')
    canonical.rel = 'canonical'
    canonical.href = this.page.seo.canonical
    document.head.appendChild(canonical)

    if (context.preview) {
      const bridge = document.createElement('script')
      bridge.src = context.bridge
      bridge.defer = true
      document.head.appendChild(bridge)
    }
  }
}
```

Links between CMS pages are plain `<a href>` links, so each one loads the next page from the server, with its own status and head. The bridge script is added only while previewing; step 7 explains it.

## 6. Write and register components

Each component an editor can place on a page gets a standalone Angular component. Open **Configuration › Components** to see your space's component keys and fields. This guide draws a `hero`, a `featureGrid` with `featureItem` cards in its `items` slot, and the `action` buttons inside the hero. Use your own keys and fields.

The component map is provided through an injection token, so components that draw nested blocks do not import the map themselves:

```ts
// src/app/blocks/registry.ts
import { InjectionToken, type Type } from '@angular/core'

export type BlockComponent = Type<unknown>

export const CMS_BLOCKS = new InjectionToken<Record<string, BlockComponent>>('CMS_BLOCKS')
```

```ts
// src/app/blocks/index.ts
import type { BlockComponent } from './registry'
import { Action } from './action'
import { FeatureGrid } from './feature-grid'
import { FeatureItem } from './feature-item'
import { Hero } from './hero'

export const blocks: Record<string, BlockComponent> = {
  hero: Hero,
  featureGrid: FeatureGrid,
  featureItem: FeatureItem,
  action: Action,
}
```

Provide it in the app's configuration:

```ts
// src/app/app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core'
import { provideClientHydration } from '@angular/platform-browser'
import { provideRouter } from '@angular/router'
import { routes } from './app.routes'
import { blocks } from './blocks'
import { CMS_BLOCKS } from './blocks/registry'

export const appConfig: ApplicationConfig = {
  providers: [
    provideBrowserGlobalErrorListeners(),
    provideRouter(routes),
    provideClientHydration(),
    { provide: CMS_BLOCKS, useValue: blocks },
  ],
}
```

`cms-blocks` draws a list of blocks with the map, through `NgComponentOutlet`:

```ts
// src/app/blocks/blocks.ts
import { Component, inject, input } from '@angular/core'
import { NgComponentOutlet } from '@angular/common'
import type { CmsComponent } from '@bifrost-orbit-cms/sdk'
import { Fallback } from './fallback'
import { CMS_BLOCKS } from './registry'

@Component({
  selector: 'cms-blocks',
  imports: [NgComponentOutlet],
  template: `
    @for (block of blocks(); track block.id) {
      <ng-container *ngComponentOutlet="registry[block.type] ?? fallback; inputs: { block }" />
    }
  `,
})
export class Blocks {
  readonly blocks = input<CmsComponent[] | undefined>([])
  protected readonly registry = inject(CMS_BLOCKS)
  protected readonly fallback = Fallback
}
```

A block with no component yet shows its type in development, and nothing in a production build:

```ts
// src/app/blocks/fallback.ts
import { Component, input, isDevMode } from '@angular/core'
import type { CmsComponent } from '@bifrost-orbit-cms/sdk'

@Component({
  selector: 'cms-fallback',
  template: `
    @if (dev) {
      <div [attr.data-cms-id]="block().id" style="border: 1px dashed; padding: 1rem">
        No component for <code>{{ block().type }}</code> yet
      </div>
    }
  `,
})
export class Fallback {
  readonly block = input.required<CmsComponent>()
  protected readonly dev = isDevMode()
}
```

The hero. Its buttons are blocks in the `primaryAction` and `secondaryAction` slots:

```ts
// src/app/blocks/hero.ts
import { Component, computed, input } from '@angular/core'
import type { CmsComponent } from '@bifrost-orbit-cms/sdk'
import { Blocks } from './blocks'

type HeroFields = { eyebrow?: string; heading: string; description?: string }

@Component({
  selector: 'cms-hero',
  imports: [Blocks],
  template: `
    <section class="hero" [attr.data-cms-id]="block().id">
      @if (fields().eyebrow) {
        <p>{{ fields().eyebrow }}</p>
      }
      <h1>{{ fields().heading }}</h1>
      <div [innerHTML]="fields().description ?? ''"></div>
      <cms-blocks [blocks]="actions()" />
    </section>
  `,
})
export class Hero {
  readonly block = input.required<CmsComponent>()
  protected readonly fields = computed(() => this.block().fields as HeroFields)
  protected readonly actions = computed(() => [
    ...(this.block().children['primaryAction'] ?? []),
    ...(this.block().children['secondaryAction'] ?? []),
  ])
}
```

```ts
// src/app/blocks/action.ts
import { Component, computed, input } from '@angular/core'
import type { CmsComponent, CmsLink } from '@bifrost-orbit-cms/sdk'

type ActionFields = { label: string; link?: CmsLink | null }

@Component({
  selector: 'cms-action',
  template: `
    @if (fields().link?.href; as href) {
      <a [attr.data-cms-id]="block().id" [href]="href" [attr.target]="fields().link?.target">{{ fields().label }}</a>
    }
  `,
})
export class Action {
  readonly block = input.required<CmsComponent>()
  protected readonly fields = computed(() => this.block().fields as ActionFields)
}
```

The feature grid and its cards:

```ts
// src/app/blocks/feature-grid.ts
import { Component, computed, input } from '@angular/core'
import type { CmsComponent } from '@bifrost-orbit-cms/sdk'
import { Blocks } from './blocks'

type FeatureGridFields = { heading: string; intro?: string }

@Component({
  selector: 'cms-feature-grid',
  imports: [Blocks],
  template: `
    <section class="feature-grid" [attr.data-cms-id]="block().id">
      <h2>{{ fields().heading }}</h2>
      @if (fields().intro) {
        <p>{{ fields().intro }}</p>
      }
      <div class="grid">
        <cms-blocks [blocks]="block().children['items']" />
      </div>
    </section>
  `,
})
export class FeatureGrid {
  readonly block = input.required<CmsComponent>()
  protected readonly fields = computed(() => this.block().fields as FeatureGridFields)
}
```

```ts
// src/app/blocks/feature-item.ts
import { Component, computed, input } from '@angular/core'
import type { CmsComponent, CmsLink } from '@bifrost-orbit-cms/sdk'

type FeatureItemFields = { title: string; body?: string; link?: CmsLink | null }

@Component({
  selector: 'cms-feature-item',
  template: `
    <article [attr.data-cms-id]="block().id">
      <h3>{{ fields().title }}</h3>
      @if (fields().body) {
        <p>{{ fields().body }}</p>
      }
      @if (fields().link?.href; as href) {
        <a [href]="href">Read more</a>
      }
    </article>
  `,
})
export class FeatureItem {
  readonly block = input.required<CmsComponent>()
  protected readonly fields = computed(() => this.block().fields as FeatureItemFields)
}
```

- **Fields** are on `block().fields`. Rich text, such as the hero's `description`, arrives as HTML; `[innerHTML]` runs it through Angular's sanitiser. Links carry `href`, which is `null` when the link points at a page that is not live, so check it first.
- **Nested blocks** are on `block().children`, one list per slot, such as `children['items']`. Each nested block has the same shape, so `cms-blocks` draws it with the map.
- **`data-cms-id`** with the block's `id` on each component's outer element lets editors click it in the live preview to select it.
- To type fields from your space's schema instead of by hand, run `npx cms-orbit generate --out src/app/cms/types.ts`, which reads the address and public key from `.env`, and use the types it writes, such as `HeroBlock`; see [The SDK](https://docs.bifrostorbit.com/cms/developers/sdk/).

**Check it:** run `npm start` and open `http://localhost:4200/`. The home page shows its hero and the rest of its blocks, a nested page such as `/products/cms-orbit` works the same way, and an unknown address answers 404 with the not-found page.

## 7. Preview drafts in the editor

The editor opens your page in a frame with a short-lived token, such as `https://stage.northwilds.com/trips/lofoten-kayak?preview=eyJ…`. The routes you added to `server.ts` in step 5 turn that into a draft view:

1. **The page route** sees `?preview=` and sends it to `/api/preview`, keeping the page's address.
2. **`/api/preview`** checks the token with `cms().checkPreview`, which asks `https://api.bifrostorbit.com/cms/preview` whether it is valid and which page it belongs to. It stores the token in an `httpOnly` cookie and redirects to that page. A missing token answers `400`, and an invalid or expired one `401`. Tokens last an hour, and the editor makes new ones as needed.
3. **The page route** checks the cookie's token on each request, so a copied or expired cookie never shows drafts. While it is valid, `resolvePage` reads the draft with the secret key and skips the cache, and the page component adds the bridge script, `https://api.bifrostorbit.com/cms/bridge.js`.
4. **`/api/preview/exit?path=/trips`** removes the cookie, for a "Leave preview" link.

The cookie is `SameSite=None` and `Secure` because the editor shows your website in a frame on another site. `safePath` keeps every redirect on your own website.

The bridge lets editors click a block in the preview to select it, and reloads the preview after each save. It selects the nearest element with `data-cms-id`, which every component from step 6 has.

**Tell CMS Orbit where the website is:** open the space's **Settings** and set **Preview URL** to the website that has the secret key, such as `https://stage.northwilds.com`. The editor adds each page's address after it.

**Check it:** open a page in the editor, change a heading and save without publishing. The preview reloads with the change. Click a block in the preview, and the editor selects it.

> **Note:** The editor frames your website from another site, so the cookie only works inside the frame over `https`, and browsers that block third-party cookies may drop it. If the preview shows the published page, use **Open in a new tab** above the preview. To show changes as editors type, without a reload, listen to the bridge in the browser; see **Show changes as editors type** in [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, when the cached page expires. With it, CMS Orbit tells your website the moment an editor publishes, and only that page is fetched again.

The `/api/cms-webhook` route in `server.ts` does this:

- It reads the body as text with `express.text`, before any parsing, so the bytes match what was signed.
- The signature in `x-orbit-signature` is the hex HMAC-SHA256 of the `x-orbit-timestamp` header, a full stop and the raw body, keyed with the webhook secret. `verifyWebhook` checks it in constant time, refuses messages more than five minutes old and reads the event from the body. A bad or old message, or a missing secret, answers `401`.
- A published page purges its own address. A moved page, a menu, a release or anything without an address purges everything, since links on other pages may have changed. It then answers `204`; any `2xx` counts as delivered.

**Create the webhook:**

1. Deploy the website, so the route has a public `https` address. Build with `npm run build` and start it with `npm run serve:ssr:northwilds-site`, or set the same variables where it runs.
2. Open **Configuration › Webhooks** and select **New webhook**. **Address:** `https://northwilds.com/api/cms-webhook`. **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 restart it.

**Check it:** in the webhook's **⋯** menu, select **Send a test**. CMS Orbit shows that the website answered `204`. Then publish a change and reload the page: the change is there straight away.

## Next steps

- [Render components](https://docs.bifrostorbit.com/cms/developers/render-blocks/): fields, 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 [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 and languages, and how to ask for them.
- [Connect a website without Next.js](https://docs.bifrostorbit.com/cms/developers/connect-any-website/), [The SDK](https://docs.bifrostorbit.com/cms/developers/sdk/) and [Metadata, sitemaps and robots with the SDK](https://docs.bifrostorbit.com/cms/developers/seo-with-the-sdk/).
- [Troubleshooting your website](https://docs.bifrostorbit.com/cms/developers/troubleshooting/).
