# Migrate from Contentful

> Move a Contentful space to CMS Orbit: how Contentful's concepts map, exporting with the Contentful CLI, turning entries, rich text, assets, references and locales into an import file, and importing it with redirects.

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

This guide moves a Contentful space into CMS Orbit in four steps: export it with the Contentful CLI, recreate the content model, transform the export into an import file, and import 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 blog posts, authors and two locales.

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

## How Contentful maps to CMS Orbit

| Contentful | CMS Orbit | Notes |
| --- | --- | --- |
| Space | Space | One website or app |
| Environment (`master`, `staging`) | Environment (Production, Staging) | CMS Orbit environments are copies of the content; editors promote from Staging to Production. The schema is shared by all of them. |
| Content type | Content type, or component | A type that has its own page becomes a content type. A type that only exists inside other entries, such as a "section" referenced from a page, usually becomes a component. See [Model your content](https://docs.bifrostorbit.com/cms/developers/model-your-content/). |
| Entry | Entry, or block | |
| Asset | File in the media library | Alt text per language |
| Locale (`en-US`, `de-DE`) | Language in a region | Each language holds its own copy of an entry, linked as translations |
| Localised field | A field whose value differs in each language's copy | |
| Fallback locale | Language fallback | Set per language |
| Reference (Link to Entry) | Reference, Link, or the referenced entry turned into blocks | |
| Rich text | Rich text (HTML), plus blocks for embedded assets and entries | Rich text cannot hold images in CMS Orbit |
| Tags, or an Array of Symbols | Taxonomy terms | |
| Slug field | The entry's slug and address | Contentful has no addresses; your website built them |
| Content Delivery and Preview API tokens | Delivery keys | See [Delivery API](https://docs.bifrostorbit.com/cms/developers/delivery-api/) |
| Webhooks | Webhooks | See [Webhooks](https://docs.bifrostorbit.com/cms/developers/webhooks/) |
| Scheduled actions, Releases | Scheduled publishing, Releases | |

Field types:

| Contentful | CMS Orbit |
| --- | --- |
| Symbol (short text) | `text`, or `select` with choices when it has an "Accept only specified values" rule |
| Text (long text) | `textarea` |
| Rich text | `richtext`, or a list of blocks |
| Integer, Number | `number` |
| Date and time | `date`, or `datetime` when the time matters |
| Boolean | `boolean` |
| Media (one or many) | `asset`, `assets` |
| Reference (one or many) | `reference`, `references`, or `link` when it only sends visitors to a page |
| Array of Symbols | `taxonomyTerms`, or `multiselect` with fixed choices |
| Location | Not yet: use two `number` fields, `latitude` and `longitude` |
| JSON object | Not yet: model the data as fields, or keep it in a `textarea` and parse it on your website |

## Before you start

- A Contentful **personal access token** (Content Management API) for the space.
- 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 20 or later.

## 1. Export the space

Install the [Contentful CLI](https://www.contentful.com/developers/docs/tutorials/cli/import-and-export/) and export the environment to one JSON file:

```bash
npm install -g contentful-cli
contentful space export \
  --space-id <space id> \
  --environment-id master \
  --management-token <CMA token> \
  --content-file contentful-export.json
```

Add `--include-drafts` to bring unpublished entries too, and `--include-archived` for archived ones. The file has `contentTypes`, `entries`, `assets` and `locales`, among others. Each entry's fields hold one value per locale:

```json
{
  "sys": { "id": "post1", "contentType": { "sys": { "id": "blogPost" } } },
  "fields": {
    "title": { "en-US": "Lofoten in winter", "nb-NO": "Lofoten om vinteren" },
    "slug": { "en-US": "lofoten-in-winter" },
    "author": { "en-US": { "sys": { "type": "Link", "linkType": "Entry", "id": "ingrid" } } }
  }
}
```

Assets are not downloaded: the file lists their addresses on `images.ctfassets.net`, and the import fetches them from there. Keep the Contentful space until the migration is finished.

## 2. Create the content model

List your content types from the export's `contentTypes`, and decide for each one whether it becomes a content type or a component, using the table above. Then 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: a `journalPost` content type with `excerpt`, `publishedOn`, `cover` and `author`, an `author` content type, and `text` and `imageBlock` components.

## 3. Transform the export

Install the two Contentful rich text packages:

```bash
npm install @contentful/rich-text-html-renderer @contentful/rich-text-types
```

The script maps each Contentful content type to a CMS Orbit one in `MAP`, turns rich text into `text` blocks with an `imageBlock` for each embedded image, rewrites links to other entries to their new addresses, and writes one translation per extra locale with only the localised values. Adjust `LOCALES`, `MAP` and `newUrl` to your space:

```js
// contentful.mjs
import { readFile, writeFile } from 'node:fs/promises'
import { documentToHtmlString } from '@contentful/rich-text-html-renderer'
import { BLOCKS, INLINES } from '@contentful/rich-text-types'

const exported = JSON.parse(await readFile(process.argv[2] ?? 'contentful-export.json', 'utf8'))

const LOCALES = { 'en-US': 'en-GB', 'nb-NO': 'nb-NO' }
const MAIN = exported.locales.find((locale) => locale.default).code

const assets = new Map(exported.assets.map((asset) => [asset.sys.id, asset]))
const entries = new Map(exported.entries.map((entry) => [entry.sys.id, entry]))
const typeOf = (entry) => entry.sys.contentType.sys.id
const value = (entry, field, locale = MAIN) => entry.fields[field]?.[locale]

const newUrl = (entry) => (typeOf(entry) === 'blogPost' ? `/journal/${value(entry, 'slug')}` : null)

function asset(link) {
  const item = link && assets.get(link.sys.id)
  const file = item && value(item, 'file')
  if (!file) return null
  const alt = Object.fromEntries(
    Object.entries(item.fields.description ?? {}).map(([locale, text]) => [LOCALES[locale], text]),
  )
  return { $asset: { url: `https:${file.url}`, filename: file.fileName, alt } }
}

function richText(document) {
  if (!document) return []
  const blocks = []
  let html = []
  const flush = () => {
    if (html.length) blocks.push({ type: 'text', fields: { text: html.join('') } })
    html = []
  }
  const options = {
    renderNode: {
      [INLINES.ENTRY_HYPERLINK]: (node, next) => {
        const target = entries.get(node.data.target.sys.id)
        const href = target && newUrl(target)
        return href ? `<a href="${href}">${next(node.content)}</a>` : next(node.content)
      },
      [INLINES.ASSET_HYPERLINK]: (node, next) => next(node.content),
      [INLINES.EMBEDDED_ENTRY]: () => '',
    },
  }
  for (const node of document.content) {
    if (node.nodeType === BLOCKS.EMBEDDED_ASSET) {
      flush()
      const image = asset(node.data.target)
      if (image) blocks.push({ type: 'imageBlock', fields: { image } })
    } else if (node.nodeType === BLOCKS.EMBEDDED_ENTRY) {
      flush()
    } else {
      html.push(documentToHtmlString({ nodeType: BLOCKS.DOCUMENT, data: {}, content: [node] }, options))
    }
  }
  flush()
  return blocks
}

const MAP = {
  person: (entry, locale) => ({
    type: 'author',
    name: value(entry, 'name'),
    fields: {
      bio: documentToHtmlString(value(entry, 'shortBio', locale) ?? { nodeType: 'document', data: {}, content: [] }),
      photo: asset(value(entry, 'image')),
    },
  }),
  blogPost: (entry, locale) => ({
    type: 'journalPost',
    name: value(entry, 'title', locale) ?? value(entry, 'title'),
    slug: value(entry, 'slug'),
    fields: {
      excerpt: value(entry, 'description', locale) ?? null,
      publishedOn: value(entry, 'publishDate')?.slice(0, 10) ?? null,
      cover: asset(value(entry, 'heroImage')),
      author: value(entry, 'author') ? { $ref: value(entry, 'author').sys.id } : null,
    },
    components: richText(value(entry, 'body', locale)),
  }),
}

const out = []
for (const entry of exported.entries) {
  const map = MAP[typeOf(entry)]
  if (!map) continue
  const main = map(entry, MAIN)
  const translations = {}
  for (const locale of exported.locales.filter((item) => !item.default)) {
    const has = Object.values(entry.fields).some((field) => field[locale.code] !== undefined)
    if (!has) continue
    const translated = map(entry, locale.code)
    translations[LOCALES[locale.code]] = {
      name: translated.name,
      fields: Object.fromEntries(Object.entries(translated.fields).filter(([, item]) => item !== null && item !== '')),
      ...(translated.components?.length ? { components: translated.components } : {}),
    }
  }
  out.push({ key: entry.sys.id, ...main, translations })
}

await writeFile('import.json', JSON.stringify({
  environment: 'staging',
  region: 'europe',
  locale: LOCALES[MAIN],
  translations: exported.locales.filter((item) => !item.default).map((item) => LOCALES[item.code]),
  entries: out,
  redirects: exported.entries
    .filter((entry) => typeOf(entry) === 'blogPost')
    .map((entry) => ({ from: `/blog/${value(entry, 'slug')}`, to: newUrl(entry) })),
}, null, 2))
console.log(`Wrote ${out.length} entries to import.json`)
```

```bash
node contentful.mjs contentful-export.json
```

What it does with the parts that need thought:

- **Rich text** becomes a list of blocks. Each run of paragraphs, headings, lists, quotes and tables becomes one `text` block of HTML. An embedded asset becomes an `imageBlock`. An embedded entry is left out: map it to a block of its own in the `for` loop if your website shows it.
- **Links to entries in rich text** become `<a href="/journal/…">` with the entry's new address. Links to assets keep only their text.
- **Locales:** CMS Orbit copies each entry into the other languages, so a translation only carries what differs. Values a locale does not have are left out, like Contentful's fallback.
- **Alt text** comes from the asset's description, per locale. Every image needs alt text in each language before publishing.
- **Addresses:** Contentful has none, so `newUrl` builds them from the slug, and `redirects` lists the old website addresses, here `/blog/{slug}`, that should move to the new ones.

## 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. See [Render components](https://docs.bifrostorbit.com/cms/developers/render-blocks/).
2. Replace calls to Contentful's Content Delivery API with the SDK: `cms.resolve({ path })` for a page, `cms.list({ type: 'journalPost' })` for an index. See [Connect a website](https://docs.bifrostorbit.com/cms/developers/connect-a-website/).
3. Point webhooks at your website instead of Contentful's, so publishing refreshes the cache. See [Webhooks](https://docs.bifrostorbit.com/cms/developers/webhooks/).
4. Promote the content to Production and deploy.
5. Check that old addresses redirect: `resolve` answers `redirect` for each imported redirect.

## What does not come across

- **Entry history and versions.** Each entry starts with one draft in CMS Orbit.
- **Scheduled publishing, tasks, comments and workflows.** Set them up again in CMS Orbit.
- **App framework apps and custom field editors.** Use CMS Orbit's field types, or keep the data in plain fields.
- **Roles and users.** People sign in with Orbit and get roles in CMS Orbit.
