# Migrate from Strapi

> Move a Strapi 5 project to CMS Orbit: how collection types, components, dynamic zones, media, relations and i18n locales map, categories as a taxonomy from CSV, reading every entry with the REST API, turning dynamic zones and Blocks rich text into an import file, and importing it with redirects.

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

Strapi and CMS Orbit both build pages from reusable components, so a Strapi project maps across closely: collection types become content types, and dynamic zones become a page's blocks. This guide reads every entry with Strapi's REST 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, authors and topics, 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 Strapi 5. Strapi 4 answers with each entry's fields under `attributes` and identifies entries by `id` instead of `documentId`, so adjust the reading code if you are still on it.

## How Strapi maps to CMS Orbit

| Strapi | CMS Orbit | Notes |
| --- | --- | --- |
| Project | Space | |
| Collection type | Content type | A type with pages of its own. Supporting types such as authors become content types too. |
| Single type, such as a homepage or footer | 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/) |
| Document (`documentId`) | Entry | |
| Component | Component | |
| Dynamic zone | The page's blocks | Each component in the zone becomes a block |
| Repeatable component inside a component | A Components slot | Nested blocks go in the slot |
| Repeatable component on a collection type | The page's blocks, or a block with a Components slot | A content type's own fields have no slot editor |
| Media library | Media library | Alt text per language |
| Relation | Reference, References, or Link | Use Link when it only sends visitors to a page |
| A "category" or "tag" collection type | Taxonomy | Editors can extend it. See [Bring categories across](#2-bring-categories-across) |
| i18n locales | Languages in a region | Each language holds its own copy of the entry, linked as translations |
| Draft and Publish | Drafts and publishing | |
| Review workflows, Releases | Reviews, Releases | |
| API tokens | Delivery keys | See [Delivery API](https://docs.bifrostorbit.com/cms/developers/delivery-api/) |
| Preview | 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:

| Strapi | CMS Orbit |
| --- | --- |
| Text (short) | `text` |
| Text (long) | `textarea` |
| Rich text (Blocks) | `richtext`, or a list of blocks |
| Rich text (Markdown) | `richtext`: convert it to HTML while you transform |
| Number | `number` |
| Date: date, datetime, time | `date`, `datetime`, `time` |
| Boolean | `boolean` |
| Email | `text` |
| Enumeration | `select` |
| Media, single or multiple | `asset`, `assets` |
| Relation | `reference`, `references` or `link` |
| UID | The entry's slug |
| Component, single | Its fields on the parent, or a `component` slot holding one block |
| Component, repeatable | `components` slot, or the page's blocks |
| Dynamic zone | The page's blocks |
| JSON | Not yet: model the data as fields |
| Password | Not supported: keep secrets out of content |
| Custom fields from plugins | A CMS Orbit field type that fits, such as `color`, or fields |

## Before you start

- A Strapi **API token** of the **Read-only** type, from **Settings › API Tokens**.
- 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

Strapi keeps the model in your project's code: each collection type in `src/api/<name>/content-types/<name>/schema.json`, and each component in `src/components/<category>/<name>.json`. For each collection type, write a CMS Orbit content type; for each component used in a dynamic zone, a component. Write them in a `schema.mjs` and create them with [Schema as code](https://docs.bifrostorbit.com/cms/developers/schema-as-code/). Keep Strapi's field names where they read well.

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

| Strapi | CMS Orbit |
| --- | --- |
| `article` with `title`, `slug`, `description`, `publishedDate`, `cover`, `author`, `topics`, `seo` and a `blocks` dynamic zone | `journalPost` |
| `author` with `name`, `slug`, `bio` (Blocks) and `avatar` | `author` |
| `topic` with `name` and `slug` | Terms of the `topics` taxonomy |
| `shared.rich-text` with a `body` (Blocks) | `text` blocks, with an `imageBlock` for each image |
| `shared.media` with `file` and `caption` | `imageBlock` |
| `gear.gear-grid` with `title` and repeatable `gear.gear-item` (`name`, `url`) | `gearList` with `gearItem` blocks in its `items` slot |

## 2. Bring categories across

A collection type that only exists to tag other entries, such as `topic` or `category`, becomes a taxonomy, and each entry a term: the entry's slug is the term's value and its name the label. The script in step 3 writes `topics.csv` in CMS Orbit's own format, with a label column per language:

```csv
value,label,label:nb-NO,label:de-DE
ski-touring,Ski touring,Topptur,Skitouren
sea-kayaking,Sea kayaking,Havpadling,Seekajak
```

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

Import it before the entries, so the `topics` field finds its terms. Terms that don't apply in a market can be hidden there afterwards, or given their own labels in a region; 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`, for scripts that move many taxonomies.

## 3. Read and transform the entries

The script reads each collection type with the [REST API](https://docs.strapi.io/cms/api/rest) (`GET /api/<plural name>`), 100 entries a page with `pagination[pageSize]`, until `meta.pagination.pageCount`. Strapi leaves media, relations, components and dynamic zones out unless you ask for them with `populate`; the dynamic zone needs a `populate[blocks][on][<component>]` line for each component in it. `status=draft` reads the latest version of every entry, published or not; leave it out to read only what is published. The script reads each locale with `locale=`, matches the translations to the main entry by `documentId`, and writes `import.json` and `topics.csv`:

```ts
// strapi.ts
import { writeFile } from 'node:fs/promises'

const STRAPI = process.env.STRAPI_URL ?? 'https://cms.northwilds.com'
const TOKEN = process.env.STRAPI_TOKEN
const SITE = 'https://northwilds.com'
const MAIN = 'en'
const LANGUAGES: Record<string, string> = { en: 'en-GB', nb: 'nb-NO', de: 'de-DE' }

type Media = { url: string; name: string; alternativeText: string | null }
type Node = {
  type: string
  text?: string
  bold?: boolean
  italic?: boolean
  underline?: boolean
  strikethrough?: boolean
  code?: boolean
  url?: string
  level?: number
  format?: 'ordered' | 'unordered'
  image?: Media
  children?: Node[]
}
type Component = { __component: string; [field: string]: unknown }
type Topic = { documentId: string; name: string; slug: string }
type Author = { documentId: string; name: string; slug: string; bio: Node[] | null; avatar: Media | null }
type Article = {
  documentId: string
  title: string
  slug: string
  description: string | null
  publishedDate: string | null
  cover: Media | null
  author: { documentId: string } | null
  topics: Topic[]
  seo: { metaTitle: string; metaDescription: string } | null
  blocks: Component[]
}

type Block = { type: string; fields: Record<string, unknown>; children?: Record<string, Block[]> }
type Entry = {
  key: string
  type: string
  name: string
  slug: string
  url?: string
  fields: Record<string, unknown>
  components?: Block[]
  seo?: { title: string; description: string }
  translations?: Record<string, Omit<Partial<Entry>, 'key' | 'type' | 'translations'>>
}

async function all<T>(collection: string, locale: string, populate: Record<string, string> = {}): Promise<T[]> {
  const items: T[] = []
  for (let page = 1; ; page += 1) {
    const params = new URLSearchParams({
      locale,
      status: 'draft',
      'pagination[page]': String(page),
      'pagination[pageSize]': '100',
      ...populate,
    })
    const response = await fetch(`${STRAPI}/api/${collection}?${params}`, {
      headers: { Authorization: `Bearer ${TOKEN}` },
    })
    if (!response.ok) throw new Error(`Strapi answered ${response.status} for ${collection}`)
    const { data, meta } = (await response.json()) as { data: T[]; meta: { pagination: { pageCount: number } } }
    items.push(...data)
    if (page >= meta.pagination.pageCount) return items
  }
}

const ARTICLE = {
  'populate[cover]': 'true',
  'populate[author]': 'true',
  'populate[topics]': 'true',
  'populate[seo]': 'true',
  'populate[blocks][on][shared.rich-text][populate]': '*',
  'populate[blocks][on][shared.media][populate]': '*',
  'populate[blocks][on][gear.gear-grid][populate]': '*',
}

const newUrl = (slug: string) => `/journal/${slug}`

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

function asset(media: Media | null | undefined) {
  if (!media) return null
  const url = media.url.startsWith('/') ? `${STRAPI}${media.url}` : media.url
  return { $asset: { url, filename: media.name, alt: media.alternativeText ?? '' } }
}

const escape = (text: string) =>
  text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')

function inline(nodes: Node[] = []): string {
  return nodes
    .map((node) => {
      if (node.type === 'link') return `<a href="${escape(localPath(node.url ?? ''))}">${inline(node.children)}</a>`
      let html = escape(node.text ?? '')
      if (node.code) html = `<code>${html}</code>`
      if (node.bold) html = `<strong>${html}</strong>`
      if (node.italic) html = `<em>${html}</em>`
      if (node.underline) html = `<u>${html}</u>`
      if (node.strikethrough) html = `<s>${html}</s>`
      return html
    })
    .join('')
}

function html(node: Node): string {
  switch (node.type) {
    case 'paragraph':
      return `<p>${inline(node.children)}</p>`
    case 'heading':
      return `<h${node.level}>${inline(node.children)}</h${node.level}>`
    case 'quote':
      return `<blockquote><p>${inline(node.children)}</p></blockquote>`
    case 'code':
      return `<p><code>${inline(node.children)}</code></p>`
    case 'list': {
      const tag = node.format === 'ordered' ? 'ol' : 'ul'
      const items = (node.children ?? []).map((item) => (item.type === 'list' ? html(item) : `<li>${inline(item.children)}</li>`))
      return `<${tag}>${items.join('')}</${tag}>`
    }
    default:
      return ''
  }
}

function richText(nodes: Node[] | null | undefined): Block[] {
  const blocks: Block[] = []
  let text: string[] = []
  const flush = () => {
    if (text.length) blocks.push({ type: 'text', fields: { text: text.join('') } })
    text = []
  }
  for (const node of nodes ?? []) {
    if (node.type === 'image') {
      flush()
      const image = asset(node.image)
      if (image) blocks.push({ type: 'imageBlock', fields: { image } })
    } else {
      text.push(html(node))
    }
  }
  flush()
  return blocks
}

const BLOCKS: Record<string, (block: Component) => Block[]> = {
  'shared.rich-text': (block) => richText(block.body as Node[]),
  'shared.media': (block) => {
    const image = asset(block.file as Media | null)
    return image ? [{ type: 'imageBlock', fields: { image, caption: block.caption ?? null } }] : []
  },
  'gear.gear-grid': (block) => [
    {
      type: 'gearList',
      fields: { heading: block.title },
      children: {
        items: (block.items as { name: string; url: string | null }[]).map((item) => ({
          type: 'gearItem',
          fields: { name: item.name, link: item.url ? { kind: 'url', href: localPath(item.url) } : null },
        })),
      },
    },
  ],
}

function blocks(zone: Component[] = []) {
  return zone.flatMap((block) => {
    const map = BLOCKS[block.__component]
    if (!map) console.warn(`No mapping for the ${block.__component} component`)
    return map ? map(block) : []
  })
}

function article(item: Article) {
  return {
    name: item.title,
    slug: item.slug,
    url: newUrl(item.slug),
    fields: {
      excerpt: item.description,
      publishedOn: item.publishedDate,
      cover: asset(item.cover),
      author: item.author ? { $ref: `author:${item.author.documentId}` } : null,
      topics: item.topics.map((topic) => topic.slug),
    },
    components: blocks(item.blocks),
    ...(item.seo ? { seo: { title: item.seo.metaTitle, description: item.seo.metaDescription } } : {}),
  }
}

function author(item: Author) {
  return {
    name: item.name,
    slug: item.slug,
    fields: { bio: richText(item.bio).map((block) => block.fields.text).filter(Boolean).join(''), photo: asset(item.avatar) },
  }
}

const others = Object.keys(LANGUAGES).filter((code) => code !== MAIN)
const read = async <T>(collection: string, populate?: Record<string, string>) =>
  Object.fromEntries(await Promise.all(Object.keys(LANGUAGES).map(async (code) => [code, await all<T>(collection, code, populate)]))) as Record<string, T[]>

const articles = await read<Article>('articles', ARTICLE)
const authors = await read<Author>('authors', { 'populate[avatar]': 'true' })
const topics = await read<Topic>('topics')

function translated<T extends { documentId: string }>(lists: Record<string, T[]>, item: T, map: (item: T) => Omit<Entry, 'key' | 'type'>) {
  const translations: Entry['translations'] = {}
  for (const code of others) {
    const other = lists[code].find((candidate) => candidate.documentId === item.documentId)
    if (other) translations[LANGUAGES[code]] = map(other)
  }
  return translations
}

const entries: Entry[] = [
  ...authors[MAIN].map((item) => ({ key: `author:${item.documentId}`, type: 'author', ...author(item), translations: translated(authors, item, author) })),
  ...articles[MAIN].map((item) => ({ key: `article:${item.documentId}`, type: 'journalPost', ...article(item), translations: translated(articles, item, article) })),
]

const cell = (value: string) => (/[",;\n]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value)
const rows = topics[MAIN].map((topic) => [
  topic.slug,
  topic.name,
  ...others.map((code) => topics[code].find((other) => other.documentId === topic.documentId)?.name ?? ''),
])
const header = ['value', 'label', ...others.map((code) => `label:${LANGUAGES[code]}`)]
await writeFile('topics.csv', [header, ...rows].map((row) => row.map(cell).join(',')).join('\n'))

await writeFile('import.json', JSON.stringify({
  environment: 'staging',
  region: 'europe',
  locale: LANGUAGES[MAIN],
  translations: others.map((code) => LANGUAGES[code]),
  entries,
  redirects: articles[MAIN].map((item) => ({ from: `/blog/${item.slug}`, to: newUrl(item.slug) })),
}, null, 2))
console.log(`Wrote ${entries.length} entries to import.json and ${rows.length} topics to topics.csv`)
```

```bash
export STRAPI_URL=https://cms.northwilds.com STRAPI_TOKEN=<read-only API token>
node strapi.ts
```

What it does with the parts that need thought:

- **Dynamic zones:** each component in the zone becomes a block through `BLOCKS`, keyed by its `__component`, such as `shared.media`. A component without a mapping is left out with a warning, so you see what is missing.
- **Nested components:** the gear grid's repeatable `items` become `gearItem` blocks in the `gearList` block's `items` slot, under `children`, as CMS Orbit stores them.
- **Rich text (Blocks)** becomes HTML: paragraphs, headings, lists, quotes, links and bold, italic, underline, strikethrough and code. An image in it becomes an `imageBlock` between `text` blocks, since rich text in CMS Orbit holds no images.
- **Rich text (Markdown)** fields hold Markdown instead. Convert them with a Markdown package such as `marked`, and split images out in the same way.
- **Media:** Strapi's local upload provider answers addresses such as `/uploads/ridge_4f2a.jpg`, so the script puts the Strapi address in front. Uploads in a cloud provider already have a full address. Each file's `alternativeText` becomes its alt text in the main language; add the other languages in the media library before publishing.
- **Relations** to authors become a `$ref` to the author's entry, by its `documentId`. The relation to topics becomes the topics' slugs, the values of the terms in `topics.csv`.
- **Locales:** Strapi 5 keeps each locale of a document under the same `documentId`, so the script reads every locale and attaches each to the main entry as a translation, with its own name, slug and address. Fields that are not localised in Strapi arrive the same in every locale, which does no harm.
- **SEO:** the `shared.seo` component from Strapi's templates gives the SEO title and description. Read your own SEO fields instead if they differ.
- **Addresses:** Strapi has none, so `newUrl` builds them from the slug, and `redirects` lists the old website addresses, here `/blog/{slug}`, that should move to `/journal/{slug}`. Add the translated addresses, such as `/nb/blog/{slug}`, in the same way if your website had them.

Single types, such as a homepage or footer, are at `GET /api/<singular name>` without pagination. Map them the same way, or make menus and global entries from them.

To keep a full copy of the project as well, export it with `npm run strapi export -- --no-encrypt --file northwilds-backup`. The archive holds every entity, relation and uploaded file as JSON lines, but without components and relations resolved into each entry, so the REST API is easier to transform.

## 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/). Running it again after changing the transform updates the entries it made.

## 5. Switch the website

1. Render the new components on your website. The SDK's registry maps each component key to your own component, so your dynamic zone components can stay as they are, registered under the new keys. See [Render components](https://docs.bifrostorbit.com/cms/developers/render-blocks/).
2. Replace calls to Strapi's REST or GraphQL API, or `@strapi/client`, with the SDK. See [Connect a website](https://docs.bifrostorbit.com/cms/developers/connect-a-website/):

   ```ts
   // Before: Strapi
   const response = await fetch(`${STRAPI}/api/articles?filters[slug][$eq]=${slug}&populate=*`)
   const article = (await response.json()).data[0]

   // After: CMS Orbit
   const result = await cms.resolve({ path: `/journal/${slug}` })
   const posts = await cms.list({ type: 'journalPost', sort: '-publishedAt', perPage: 12 })
   ```

3. Replace Strapi's preview with CMS Orbit's live preview, and mark blocks with `data-cms-id` so editors can click them. See [Set up the live preview](https://docs.bifrostorbit.com/cms/developers/preview/).
4. Point webhooks at your website instead of Strapi's. See [Webhooks](https://docs.bifrostorbit.com/cms/developers/webhooks/).
5. Promote the content to Production, deploy, and check that old addresses redirect.

## What does not come across

- **Content history and versions.** Each entry starts with one draft.
- **Review workflow stages, releases and assignees.** Set them up again in CMS Orbit.
- **Plugins, custom fields, lifecycle hooks and custom controllers.** Use CMS Orbit's field types, webhooks and the Management API instead.
- **JSON fields.** Model the data as fields.
- **Roles, users and API tokens.** People sign in with Orbit and get roles in CMS Orbit; create new delivery keys.
