# Schema as code

> Keep your content types and components in your repository and create or change them from a script or CI with the Management API, with a dry run, safe field changes and generated types.

Source: https://docs.bifrostorbit.com/cms/developers/schema-as-code/

Editors can build the schema under **Schema** in CMS Orbit, but many teams prefer to keep it next to the website code: reviewed in pull requests, the same in every space, and changed in the same commit as the components that render it. This guide sets that up with a definition file, a sync script and a CI job. It uses Node 20 or later and no packages.

The [command line](https://docs.bifrostorbit.com/cms/developers/cli/) does all of this for you: `cms-orbit schema init` writes the schema as typed TypeScript files, and `schema validate`, `schema diff`, `schema push` and `schema rollback` check, compare, apply and undo it, with a snapshot before every push. This guide shows how it works underneath, for when you want your own script.

## Before you start

- A **management token** (`cms_mt_…`) from **Organisation › Management tokens**, created by someone allowed to change the schema. The token acts as that person. A read-only token is enough for the dry run.
- Your **organisation id** and **space id**: they are in the CMS address, `/o/{organisationId}/s/{spaceId}/`.
- Know that **the schema belongs to the space, not to an environment.** A change reaches Staging and Production at once, so make it safe for the website that is live (see "Change fields safely" below).

## What the API offers

| Method and address | Does |
| --- | --- |
| `GET /components`, `GET /content-types` | Lists every definition |
| `GET /components/{key}`, `GET /content-types/{key}` | Reads one, or `404` |
| `POST /components`, `POST /content-types` | Creates one. `409` if the key exists. |
| `PATCH /components/{key}`, `PATCH /content-types/{key}` | Changes one. `fields` replaces the whole list. |
| `DELETE /components/{key}`, `DELETE /content-types/{key}` | Deletes one. Refused while entries or pages use it. |

All addresses start with `https://api.bifrostorbit.com/cms/manage/v1/organisations/{organisationId}/spaces/{spaceId}`. Every property and limit is in the [Management API](https://docs.bifrostorbit.com/cms/developers/management-api/) reference, and field settings in [Field types](https://docs.bifrostorbit.com/cms/developers/field-types/).

Things to know before you script it:

- **Keys are fixed.** A component's or content type's `key`, and a field's `key`, cannot be renamed.
- **`fields` is the whole list.** A `PATCH` with `fields` replaces every field, so always send all of them, in order.
- **Slots must say what they accept.** A `component` or `components` field needs `allowedComponents`.
- **The address prefix is set by update only.** `urlPrefix` on a content type, such as `/journal`, can be sent with `PATCH`, not `POST`. It is accepted only while every entry already lives under it, so set it before entries exist.
- **The schema version moves** each time a definition's fields change. Entries keep every value they hold.

## 1. Describe the schema

Make a folder `cms/` in your repository with a client, the definitions and the sync script. First the client, which the [Import content](https://docs.bifrostorbit.com/cms/developers/import-content/) guide uses too:

```js
// cms/orbit.mjs
const API = process.env.ORBIT_API ?? 'https://api.bifrostorbit.com/cms/manage/v1'
const TOKEN = process.env.ORBIT_TOKEN
const BASE = `${API}/organisations/${process.env.ORBIT_ORGANISATION}/spaces/${process.env.ORBIT_SPACE}`

export async function call(method, path, body) {
  const isForm = body instanceof FormData
  for (let attempt = 1; ; attempt += 1) {
    const response = await fetch(`${BASE}${path}`, {
      method,
      headers: { authorization: `Bearer ${TOKEN}`, ...(body && !isForm ? { 'content-type': 'application/json' } : {}) },
      body: isForm ? body : body === undefined ? undefined : JSON.stringify(body),
    })
    if (response.status === 204) return null
    const json = await response.json().catch(() => ({}))
    if (response.ok) return json.data
    if (response.status >= 500 && attempt < 4) {
      await new Promise((resolve) => setTimeout(resolve, 1000 * attempt))
      continue
    }
    const error = new Error(`${method} ${path} answered ${response.status}: ${json.error?.message ?? response.statusText}`)
    error.status = response.status
    error.details = json.error?.details
    throw error
  }
}

export async function findScope({ environment, region, locale }) {
  const environments = await call('GET', '/environments')
  const env = environments.find((entry) => entry.key === environment)
  if (!env) throw new Error(`No environment "${environment}"`)
  const regions = await call('GET', `/environments/${env.id}/regions`)
  const reg = regions.find((entry) => entry.key === region)
  if (!reg) throw new Error(`No region "${region}"`)
  const locales = await call('GET', `/environments/${env.id}/regions/${reg.id}/locales`)
  const loc = locales.find((entry) => entry.code === locale)
  if (!loc) throw new Error(`No language "${locale}" in ${region}`)
  return {
    environmentId: env.id,
    regionId: reg.id,
    localeId: loc.id,
    code: loc.code,
    path: `/environments/${env.id}/regions/${reg.id}/locales/${loc.id}`,
  }
}
```

Then the definitions. This is the Northwilds journal from [Model your content](https://docs.bifrostorbit.com/cms/developers/model-your-content/). Each object is what you would `POST`:

```js
// cms/schema.mjs
export const components = [
  {
    key: 'text',
    name: 'Text',
    group: 'Journal',
    fields: [{ key: 'text', name: 'Text', type: 'richtext', required: true }],
  },
  {
    key: 'textSection',
    name: 'Text section',
    group: 'Journal',
    fields: [
      { key: 'heading', name: 'Heading', type: 'text', required: true },
      { key: 'level', name: 'Heading level', type: 'select', default: 'h2', options: [{ label: 'H2', value: 'h2' }, { label: 'H3', value: 'h3' }] },
      { key: 'text', name: 'Text', type: 'richtext' },
    ],
  },
  {
    key: 'imageBlock',
    name: 'Image',
    group: 'Journal',
    fields: [
      { key: 'image', name: 'Image', type: 'asset', required: true, allowedMimeTypes: ['image/*'] },
      { key: 'caption', name: 'Caption', type: 'text' },
    ],
  },
  {
    key: 'gearList',
    name: 'Gear list',
    group: 'Gear',
    fields: [
      { key: 'heading', name: 'Heading', type: 'text', required: true },
      { key: 'items', name: 'Items', type: 'components', allowedComponents: ['gearItem'] },
    ],
  },
  {
    key: 'gearItem',
    name: 'Gear item',
    group: 'Gear',
    isRoot: false,
    fields: [
      { key: 'name', name: 'Name', type: 'text', required: true },
      { key: 'link', name: 'Link', type: 'link' },
    ],
  },
]

export const contentTypes = [
  {
    key: 'author',
    name: 'Author',
    fields: [
      { key: 'bio', name: 'Biography', type: 'richtext' },
      { key: 'photo', name: 'Photo', type: 'asset' },
    ],
  },
  {
    key: 'journalPost',
    name: 'Journal post',
    urlPrefix: '/journal',
    fields: [
      { key: 'excerpt', name: 'Excerpt', type: 'textarea', validation: { maxLength: 300 } },
      { key: 'publishedOn', name: 'Published on', type: 'date' },
      { key: 'author', name: 'Author', type: 'reference', allowedContentTypes: ['author'] },
      { key: 'cover', name: 'Cover image', type: 'asset' },
      { key: 'topics', name: 'Topics', type: 'taxonomyTerms', taxonomyKey: 'topics' },
    ],
    allowedComponents: ['text', 'textSection', 'imageBlock', 'gearList', 'sharedSection'],
  },
]
```

- `isRoot: false` keeps `gearItem` out of the page's top level, so it is only offered inside a gear list.
- `sharedSection` in `allowedComponents` lets editors place shared sections on posts.
- Components come first in the file, because content types and slots name them.

Slider, Star rating, Code block and Palette fields take their settings in the same object:

```js
{
  key: 'tripFacts',
  name: 'Trip facts',
  fields: [
    { key: 'difficulty', name: 'Difficulty', type: 'slider', validation: { min: 1, max: 10 }, step: 0.5, unit: 'of 10', default: 5 },
    { key: 'rating', name: 'Guide rating', type: 'rating', validation: { max: 5 }, halfStars: true },
    { key: 'mapEmbed', name: 'Map embed', type: 'code', languages: ['html'], defaultLanguage: 'html' },
    { key: 'accent', name: 'Accent', type: 'palette', options: [{ label: 'Fjord blue', value: '#1F4E79' }, { label: 'Moss green', value: '#4A6B3A' }] },
  ],
}
```

Saving refuses a slider whose lowest value isn't below its highest, a step bigger than the range, a rating with fewer than 3 or more than 10 stars, a starting language that isn't among `languages`, and a palette colour that isn't a hex code. `cms-orbit schema validate` checks the same before you push.

## 2. Write the sync script

The script reads each definition, compares it with the space and creates or updates it. It prints what it would do and changes nothing unless you pass `--apply`. It stops before a field changes type, and before a field is removed unless you pass `--allow-removals`. It never deletes a component or content type: do that in CMS Orbit, which shows where each one is still used.

```js
// cms/sync-schema.mjs
import { call } from './orbit.mjs'
import { components, contentTypes } from './schema.mjs'

const apply = process.argv.includes('--apply')
const allowRemovals = process.argv.includes('--allow-removals')

async function current(path) {
  try {
    return await call('GET', path)
  } catch (error) {
    if (error.status === 404) return null
    throw error
  }
}

function fieldChanges(before, after) {
  const old = new Map((before ?? []).map((field) => [field.key, field]))
  const next = new Map(after.map((field) => [field.key, field]))
  return [
    ...[...next.keys()].filter((key) => !old.has(key)).map((key) => `+${key}`),
    ...[...old.keys()].filter((key) => !next.has(key)).map((key) => `-${key}`),
    ...[...next.keys()].filter((key) => old.has(key) && old.get(key).type !== next.get(key).type).map((key) => `~${key}`),
  ]
}

async function sync(kind, path, definition) {
  const existing = await current(`${path}/${definition.key}`)
  const changes = fieldChanges(existing?.fields, definition.fields)
  if (changes.some((change) => change.startsWith('~'))) {
    throw new Error(`${kind} ${definition.key}: a field changes type (${changes.join(' ')}). Add a new field instead.`)
  }
  if (!allowRemovals && changes.some((change) => change.startsWith('-'))) {
    throw new Error(`${kind} ${definition.key}: fields would be removed (${changes.join(' ')}). Run with --allow-removals once the website no longer reads them.`)
  }
  console.log(`${existing ? 'update' : 'create'} ${kind} ${definition.key} ${changes.join(' ')}`.trim())
  if (!apply) return
  if (existing) {
    const { key, ...rest } = definition
    await call('PATCH', `${path}/${key}`, rest)
  } else {
    await call('POST', path, definition)
    if (definition.urlPrefix) await call('PATCH', `${path}/${definition.key}`, { urlPrefix: definition.urlPrefix })
  }
}

for (const component of components) await sync('component', '/components', component)
for (const type of contentTypes) await sync('content type', '/content-types', type)
if (!apply) console.log('Dry run. Run again with --apply to make these changes.')
```

## 3. Run it

```bash
export ORBIT_TOKEN=cms_mt_…
export ORBIT_ORGANISATION=<organisation id>
export ORBIT_SPACE=<space id>

node cms/sync-schema.mjs
```

```
create component text +text
create component textSection +heading +level +text
create component imageBlock +image +caption
create component gearList +heading +items
create component gearItem +name +link
update content type author
create content type journalPost +excerpt +publishedOn +author +cover +topics
Dry run. Run again with --apply to make these changes.
```

`+` is a new field, `-` a removed one. Check the list, then run `node cms/sync-schema.mjs --apply`. Running it again changes nothing that is already the same: a `PATCH` with identical fields does not move the schema version.

If the space refuses a definition, the script stops with the reason, such as `PATCH /content-types/journalPost answered 400: Some entries live elsewhere, such as /lofoten-in-winter. Move every entry under /journal first, so no address changes.` Status codes and their fixes are in [Error codes](https://docs.bifrostorbit.com/cms/developers/error-codes/).

## 4. Run it from CI

Run the dry run on every pull request and apply on the main branch. This GitHub Actions workflow keeps the token in a repository secret:

```yaml
# .github/workflows/cms-schema.yml
name: CMS schema
on:
  pull_request:
    paths: ['cms/**']
  push:
    branches: [main]
    paths: ['cms/**']

jobs:
  schema:
    runs-on: ubuntu-latest
    env:
      ORBIT_TOKEN: ${{ github.event_name == 'push' && secrets.ORBIT_TOKEN || secrets.ORBIT_READ_TOKEN }}
      ORBIT_ORGANISATION: ${{ vars.ORBIT_ORGANISATION }}
      ORBIT_SPACE: ${{ vars.ORBIT_SPACE }}
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 24
      - run: node cms/sync-schema.mjs ${{ github.event_name == 'push' && '--apply' || '' }}
```

- Give pull requests a **read-only** token (`ORBIT_READ_TOKEN`), so a pull request can never change the schema.
- Tokens expire after at most 365 days. Note the date and renew it before then, or the job fails with `401`.
- After applying, regenerate the website's types with `npx cms-orbit generate --out src/cms/types.ts` in the same pipeline, so a schema change that breaks the website fails its build. See [SDK](https://docs.bifrostorbit.com/cms/developers/sdk/).

## Change fields safely

Because the schema is shared by every environment, a change must work for the website that is live now and for the one you are about to deploy. Entries keep every value they hold; nothing is converted or erased.

| Change | Do it in this order |
| --- | --- |
| Add an optional field | Apply the schema, regenerate types, deploy a website that handles the empty value |
| Add a required field | Add it as optional, let editors fill it in, then make it required. Publishing is refused while a required field is empty. |
| Rename a field | Not possible: add a field with the new key, copy the values with a script (see [Import content](https://docs.bifrostorbit.com/cms/developers/import-content/)), then remove the old one |
| Change a field's type | Add a new field of the new type, move the content, then remove the old one. The script refuses a type change. |
| Remove a field | Deploy a website that no longer reads it, then run with `--allow-removals`. Values stay stored, and adding the key again brings them back. |
| Remove a component | Remove it from every page first, then delete it in **Schema › Components**. Deleting a component in use is refused with `409`, naming the pages. |

[Field types](https://docs.bifrostorbit.com/cms/developers/field-types/) has the full table under "Change or remove a field safely".

## Several spaces

To keep a staging space and a production space alike, or one schema across many websites, run the same script once per space with a different `ORBIT_SPACE`. For a one-off copy of every definition from one space to another, use **Download JSON** in one space's settings and **Import…** in the other's: the import adds what is missing and leaves anything with the same key as it is. See [Space settings](https://docs.bifrostorbit.com/cms/editors/space-settings/).
