# Migrate from Prismic

> Move a Prismic repository to CMS Orbit: how custom types, slices, slice zones, locales and Integration Fields map, tags as a taxonomy from CSV, reading every document with the Content API, turning slices and rich text into an import file with a link resolver, and importing it with redirects.

Source: https://docs.bifrostorbit.com/cms/developers/migrate-from-prismic/

Prismic and CMS Orbit share an idea: developers build components in code, and editors put pages together from them. Prismic calls them slices; CMS Orbit calls them components. So a slice zone maps across one to one, and most of the work is in rich text and links. This guide reads every document with Prismic's Content API, turns it into an import file, and imports it with the script from [Import content with the Management API](https://docs.bifrostorbit.com/cms/developers/import-content/). The examples move a Northwilds journal with articles and authors, in English with Norwegian and German translations.

For the project around it, from the content inventory to the weeks after launch, see [Plan a migration to CMS Orbit](https://docs.bifrostorbit.com/cms/developers/plan-a-migration/).

The guide is written for the Content API v2 and `@prismicio/client` 7.

## How Prismic maps to CMS Orbit

| Prismic | CMS Orbit | Notes |
| --- | --- | --- |
| Repository | Space | |
| Repeatable page type | Content type | |
| Single type, such as a homepage or settings | An entry, a global entry or a menu | See [Menus, site-wide content and lists](https://docs.bifrostorbit.com/cms/developers/menus-globals-and-lists/) |
| Custom type without pages, such as an author | Content type | Its entries get an address too; decide whether your website shows it |
| Document | Entry | |
| Slice | Component | |
| Slice zone | The page's blocks | |
| Slice variation | A `select` field on the component, such as `layout` | Or separate components when the variations hold different fields |
| Repeatable group in a slice | A Components slot | Each item becomes a block in the slot |
| Shared slice used on many pages with the same content | Shared section | |
| Media library | Media library | Alt text per language |
| Content relationship | Reference, References, or Link | |
| Link resolver and route resolver | Addresses from the content type's prefix and the entry's slug | CMS Orbit builds addresses itself |
| Tags | Taxonomy | See [Bring tags across](#2-bring-tags-across) |
| Locales | Languages in a region | Each language holds its own copy of the entry, linked as translations |
| Releases and scheduling | Releases and scheduled publishing | |
| Integration Fields | A Commerce Orbit Product field, or plain fields | CMS Orbit has no JSON field |
| Preview with the toolbar | Live preview with click-to-select | See [Set up the live preview](https://docs.bifrostorbit.com/cms/developers/preview/) |
| Webhooks | Webhooks | See [Webhooks](https://docs.bifrostorbit.com/cms/developers/webhooks/) |

Field types:

| Prismic | CMS Orbit |
| --- | --- |
| Key text | `text` |
| Rich text | `richtext`, or a list of blocks |
| Rich text set to one heading (a title) | `text` |
| UID | The entry's slug |
| Number | `number` |
| Boolean | `boolean` |
| Date, Timestamp | `date`, `datetime` |
| Select | `select` |
| Color | `color` |
| Image | `asset`, with alt text in the media library |
| Link | `link` |
| Link to media | `link` to a file, or `asset` |
| Content relationship | `reference`, `references` or `link` |
| Embed | A component with a `text` field for the address, such as a video block |
| Geopoint | Not yet: use two `number` fields |
| Group | A Components slot, or fields on the parent |
| Table | `richtext` holding an HTML table |
| Integration | `product` or `products` for items from Commerce Orbit, otherwise the values you need as fields |

## Before you start

- The repository's name, and a **Content API access token** if the API is private, from **Settings › API & Security**.
- In CMS Orbit: a space with Staging, a region and every language you need, and a management token. See "Before you start" in [Import content with the Management API](https://docs.bifrostorbit.com/cms/developers/import-content/).
- Node 24, which runs the TypeScript scripts below as they are. Work in a folder whose `package.json` has `"type": "module"`, such as one made with `npm init -y && npm pkg set type=module`.

## 1. Recreate the model

With Slice Machine, each page type is in `customtypes/<id>/index.json` and each slice in `slices/<Library>/<Name>/model.json`, in your website's code. For each page type, write a CMS Orbit content type; for each slice, a component, with a Components slot for each repeatable group. Write them in a `schema.mjs` and create them with [Schema as code](https://docs.bifrostorbit.com/cms/developers/schema-as-code/).

The script below assumes the journal model from that guide, plus these Prismic types:

| Prismic | CMS Orbit |
| --- | --- |
| `article` with `uid`, `title`, `excerpt`, `published`, `cover`, `author`, `meta_title`, `meta_description` and a slice zone | `journalPost` |
| `author` with `name`, `bio` and `photo` | `author` |
| `rich_text` slice with `content` | `text` blocks, with an `imageBlock` for each image |
| `image` slice with `image` and `caption` | `imageBlock` |
| `gear_grid` slice with `title` and an `items` group of `name` and `link` | `gearList` with `gearItem` blocks in its `items` slot |
| Tags | Terms of the `topics` taxonomy |

## 2. Bring tags across

Prismic tags are free text on each document. They become a taxonomy, so editors pick from a list and websites can filter by them: each tag becomes a term, its text the label and a slug of it the value, so `Ski touring` becomes `ski-touring`. The script in step 3 writes them to `topics.csv`:

1. In CMS Orbit, open **Schema › Taxonomies** and create the taxonomy, with the key `topics`.
2. Choose **Import CSV** and pick `topics.csv`. The preview shows each term as new; choose **Import**.

Tags have no translations in Prismic. Add the Norwegian and German labels to the file as `label:nb-NO` and `label:de-DE` columns before importing, or in CMS Orbit later; see [Tag content with taxonomies](https://docs.bifrostorbit.com/cms/editors/taxonomies/). The [Management API](https://docs.bifrostorbit.com/cms/developers/management-api/) imports the same file with `POST /taxonomies/topics/import`.

## 3. Read and transform the documents

Install Prismic's client:

```bash
npm install @prismicio/client
```

The script reads every document in every locale with `dangerouslyGetAll({ lang: '*' })`, which pages through the [Content API](https://prismic.io/docs/content-api)'s `/api/v2/documents/search` 100 documents at a time, on the master ref. It joins each document to its translations through `alternate_languages`, converts each slice with `SLICES` and each document with `TYPES`, turns rich text into HTML with `asHTML` and a link resolver, and writes `import.json` and `topics.csv`:

```ts
// prismic.ts
import { writeFile } from 'node:fs/promises'
import { asHTML, asText, createClient, isFilled } from '@prismicio/client'
import type { ImageField, LinkField, LinkResolverFunction, PrismicDocument, RichTextField, RTNode, Slice } from '@prismicio/client'

const client = createClient(process.env.PRISMIC_REPOSITORY ?? 'northwilds', {
  accessToken: process.env.PRISMIC_TOKEN,
})
const SITE = 'https://northwilds.com'
const MAIN = 'en-gb'
const LANGUAGES: Record<string, string> = { 'en-gb': 'en-GB', 'nb-no': 'nb-NO', 'de-de': 'de-DE' }

type AnySlice = Slice<string, Record<string, any>>
type Block = { type: string; fields: Record<string, unknown>; children?: Record<string, Block[]> }
type Converted = {
  type: string
  name: string
  slug: string
  url?: string
  fields: Record<string, unknown>
  components?: Block[]
  seo?: { title: string | null; description: string | null }
}

const documents = await client.dangerouslyGetAll({ lang: '*' })
const byId = new Map(documents.map((doc) => [doc.id, doc]))

const mainOf = (id: string) => {
  const doc = byId.get(id)
  if (!doc || doc.lang === MAIN) return id
  return doc.alternate_languages.find((other) => other.lang === MAIN)?.id ?? id
}

const newUrl = (type: string | undefined, uid: string | null | undefined) =>
  type === 'article' && uid ? `/journal/${uid}` : null

const linkResolver: LinkResolverFunction = (link) => newUrl(link.type, link.uid)

function localPath(href: string) {
  const path = href.startsWith(SITE) ? href.slice(SITE.length) || '/' : href
  return path.replace(/^(\/[a-z]{2}-[a-z]{2})?\/blog\//, '/journal/')
}

function asset(image: ImageField | undefined) {
  if (!isFilled.image(image)) return null
  const url = image.url.split('?')[0]
  return { $asset: { url, filename: url.split('/').pop(), alt: image.alt ?? '' } }
}

function link(field: LinkField | undefined) {
  if (!isFilled.link(field)) return null
  if (field.link_type === 'Document') return { $link: mainOf(field.id) }
  if (field.link_type === 'Web') return { kind: 'url', href: localPath(field.url) }
  if (field.link_type === 'Media') return { kind: 'url', href: field.url }
  return null
}

function richText(field: RichTextField | undefined): Block[] {
  const blocks: Block[] = []
  let text: RTNode[] = []
  const flush = () => {
    const html = asHTML(text as RichTextField, { linkResolver })
    if (html) blocks.push({ type: 'text', fields: { text: html } })
    text = []
  }
  for (const node of field ?? []) {
    if (node.type === 'image') {
      flush()
      const image = asset(node)
      if (image) blocks.push({ type: 'imageBlock', fields: { image } })
    } else if (node.type === 'embed') {
      flush()
      console.warn(`Left out an embed: ${node.oembed.embed_url}`)
    } else {
      text.push(node)
    }
  }
  flush()
  return blocks
}

const SLICES: Record<string, (slice: AnySlice) => Block[]> = {
  rich_text: (slice) => richText(slice.primary.content),
  image: (slice) => {
    const image = asset(slice.primary.image)
    return image ? [{ type: 'imageBlock', fields: { image, caption: slice.primary.caption ?? null } }] : []
  },
  gear_grid: (slice) => [
    {
      type: 'gearList',
      fields: { heading: slice.primary.title },
      children: {
        items: (slice.primary.items as { name: string; link: LinkField }[]).map((item) => ({
          type: 'gearItem',
          fields: { name: item.name, link: link(item.link) },
        })),
      },
    },
  ],
}

function slices(zone: AnySlice[] = []) {
  return zone.flatMap((slice) => {
    const map = SLICES[slice.slice_type]
    if (!map) console.warn(`No mapping for the ${slice.slice_type} slice`)
    return map ? map(slice) : []
  })
}

const slugify = (text: string) =>
  text
    .toLowerCase()
    .replace(/ø/g, 'o')
    .replace(/æ/g, 'ae')
    .replace(/ß/g, 'ss')
    .normalize('NFKD')
    .replace(/[̀-ͯ]/g, '')
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')

const TYPES: Record<string, (doc: PrismicDocument) => Converted> = {
  author: (doc) => ({
    type: 'author',
    name: doc.data.name,
    slug: doc.uid ?? slugify(doc.data.name),
    fields: { bio: asHTML(doc.data.bio, { linkResolver }) ?? '', photo: asset(doc.data.photo) },
  }),
  article: (doc) => ({
    type: 'journalPost',
    name: asText(doc.data.title) ?? doc.id,
    slug: doc.uid ?? doc.id,
    url: newUrl(doc.type, doc.uid) ?? undefined,
    fields: {
      excerpt: doc.data.excerpt ?? null,
      publishedOn: doc.data.published ?? null,
      cover: asset(doc.data.cover),
      author: isFilled.contentRelationship(doc.data.author) ? { $ref: mainOf(doc.data.author.id) } : null,
      topics: doc.tags.map(slugify),
    },
    components: slices(doc.data.slices),
    seo: { title: doc.data.meta_title ?? null, description: doc.data.meta_description ?? null },
  }),
}

const entries = documents
  .filter((doc) => doc.lang === MAIN && TYPES[doc.type])
  .map((doc) => {
    const translations: Record<string, Omit<Converted, 'type'>> = {}
    for (const other of doc.alternate_languages) {
      const translated = byId.get(other.id)
      if (!translated || !LANGUAGES[other.lang]) continue
      const { type, ...rest } = TYPES[doc.type](translated)
      translations[LANGUAGES[other.lang]] = rest
    }
    return { key: doc.id, ...TYPES[doc.type](doc), translations }
  })

const tags = new Set(documents.flatMap((doc) => doc.tags))
const cell = (value: string) => (/[",;\n]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value)
await writeFile('topics.csv', ['value,label', ...[...tags].map((tag) => [slugify(tag), tag].map(cell).join(','))].join('\n'))

const articles = documents.filter((doc) => doc.type === 'article' && doc.uid)
await writeFile('import.json', JSON.stringify({
  environment: 'staging',
  region: 'europe',
  locale: LANGUAGES[MAIN],
  translations: Object.keys(LANGUAGES).filter((code) => code !== MAIN).map((code) => LANGUAGES[code]),
  entries,
  redirects: articles.map((doc) => ({
    from: doc.lang === MAIN ? `/blog/${doc.uid}` : `/${doc.lang}/blog/${doc.uid}`,
    to: doc.lang === MAIN ? `/journal/${doc.uid}` : `/${doc.lang.slice(0, 2)}/journal/${doc.uid}`,
  })),
}, null, 2))
console.log(`Wrote ${entries.length} entries to import.json and ${tags.size} tags to topics.csv`)
```

```bash
export PRISMIC_REPOSITORY=northwilds PRISMIC_TOKEN=<access token>
node prismic.ts
```

What it does with the parts that need thought:

- **Slices** map one to one through `SLICES`, keyed by `slice_type`. A slice without a mapping is left out with a warning, so you see what is missing. The script reads `slice.primary`; slices made before repeatable groups existed keep their repeatable fields in `slice.items` instead.
- **Repeatable groups** in a slice, here the gear grid's `items`, become blocks in the `gearList` block's `items` slot, under `children`.
- **Rich text** arrives as structured JSON: a list of nodes such as `{ "type": "paragraph", "text": "…", "spans": [ … ] }`. `asHTML` turns each run of text nodes into one `text` block of HTML, with headings, lists, bold, italic and links. An image node becomes an `imageBlock`, since rich text in CMS Orbit holds no images. An embed is left out with a warning: map it to a video or embed component of your own if your website shows it.
- **The link resolver** gives a document link inside rich text its new address, so a link to an article becomes `<a href="/journal/…">`. Return the address for each type your website links to.
- **Links and relationships:** a Link field to a document becomes a link to its new entry, so it follows the page when it moves; a link to your own domain becomes a plain address on the site. A content relationship to an author becomes a `$ref`. Both point at the document in the main locale, found through `alternate_languages`, since CMS Orbit links the translations itself.
- **Images:** the script takes the query off Prismic's image address, such as `?auto=format,compress`, so the original file is uploaded. CMS Orbit resizes by address itself. The image's `alt` becomes its alt text in the main language; add the others before publishing.
- **Locales:** each locale of a document is a document of its own in Prismic, joined by `alternate_languages`. The main locale's document becomes the entry and the others its translations, with their own name, slug and address. Prismic writes locale codes in lower case, such as `nb-no`; `LANGUAGES` maps them to CMS Orbit's codes.
- **Addresses:** the old route resolver's addresses, here `/blog/:uid` and `/:lang/blog/:uid`, become redirects to `/journal/:uid`. The translated targets assume a language folder such as `/nb`; use your own address pattern from [Regions and languages](https://docs.bifrostorbit.com/cms/developers/regions-and-languages/).
- **Drafts:** the master ref holds only what is published. To bring a release across, pass its ref as `ref` to `dangerouslyGetAll`.

### Integration Fields

An Integration Field holds a copy of an item from a catalogue, such as a product from a shop, as a JSON object. CMS Orbit has no JSON field. If the products move to Commerce Orbit, use a Product or Products field, which reads the live product instead of a copy. Otherwise keep what your website needs, usually the item's id or handle, in a `text` field, and fetch the rest from the catalogue as before.

## 4. Import

Check the file with a dry run, then run the import, with `cms-orbit` from [Import content with the Management API](https://docs.bifrostorbit.com/cms/developers/import-content/):

```bash
npx cms-orbit import import.json --dry-run
npx cms-orbit import import.json
```

Check the entries in CMS Orbit on Staging, then run it again with `--publish`, or publish them in CMS Orbit. Promote them to Production with their redirects as described in [Plan a migration](https://docs.bifrostorbit.com/cms/developers/plan-a-migration/).

## 5. Switch the website

1. Register your slice components under the new component keys. With the SDK, a component gets `block` with its fields, and nested blocks as `block.items` or through `CmsBlocks`. See [Render components](https://docs.bifrostorbit.com/cms/developers/render-blocks/).
2. Replace `@prismicio/client` calls and `<SliceZone>` with the SDK. See [Connect a website](https://docs.bifrostorbit.com/cms/developers/connect-a-website/):

   ```ts
   // Before: Prismic
   const page = await client.getByUID('article', uid, { lang: 'nb-no' })
   // <SliceZone slices={page.data.slices} components={components} />

   // After: CMS Orbit
   const result = await cms.resolve({ path: `/journal/${slug}`, locale: 'nb-NO' })
   // <CmsPage page={page} registry={registry} />
   ```

3. Rich text arrives as HTML: replace `<PrismicRichText>` with `<RichText value={block.text} />`, and `<PrismicNextImage>` with `CmsImage`. See [SDK](https://docs.bifrostorbit.com/cms/developers/sdk/).
4. Replace Prismic's toolbar and preview route with CMS Orbit's live preview, and mark blocks with `data-cms-id`. See [Set up the live preview](https://docs.bifrostorbit.com/cms/developers/preview/).
5. Point webhooks at your website. See [Webhooks](https://docs.bifrostorbit.com/cms/developers/webhooks/).
6. Promote the content to Production, deploy, and check that old addresses redirect.

## What does not come across

- **Document history and versions.** Each entry starts with one draft.
- **Drafts outside a release, releases and scheduled publishing.** Publish or schedule them again in CMS Orbit.
- **Integration Fields and their catalogues.** See [Integration Fields](#integration-fields).
- **Embeds inside rich text.** Map them to components, as above.
- **Roles, users and access tokens.** People sign in with Orbit and get roles in CMS Orbit; create new delivery keys.
