# Migrate from Payload

> Move a Payload 3 project to CMS Orbit: how collections, globals, blocks fields, relationships, uploads, localization and drafts map, categories as a taxonomy from CSV, reading every document with the REST or Local API, turning blocks and Lexical rich text into an import file, and importing it with redirects.

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

In Payload, the content model is code in your `payload.config.ts` and the content is in your own database. This guide recreates the model in CMS Orbit, reads every document with Payload'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 posts, authors and categories, 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 Payload 3 with the Lexical rich text editor. Payload 2 projects that still use Slate store rich text differently; convert it with a Slate serialiser instead.

## How Payload maps to CMS Orbit

| Payload | CMS Orbit | Notes |
| --- | --- | --- |
| Project and its database | Space | |
| Collection | Content type | |
| Global, such as a header or footer | A menu or a global entry | See [Menus, site-wide content and lists](https://docs.bifrostorbit.com/cms/developers/menus-globals-and-lists/) |
| Document | Entry | One `id` across all locales |
| Block in a blocks field | Component | |
| Blocks field, such as `layout` | The page's blocks, or a Components slot | |
| Array field | A Components slot, or the page's blocks | Each row becomes a block |
| Group field | Its fields on the parent, or a `component` slot holding one block | |
| Upload collection, such as `media` | Media library | Alt text per language |
| Relationship | Reference, References, or Link | |
| Polymorphic relationship (`relationTo` several collections) | Reference or References allowing several content types | |
| Categories collection | Taxonomy | Editors can extend it. See [Bring categories across](#2-bring-categories-across) |
| Localization | Languages in a region | Each language holds its own copy of the entry, linked as translations |
| Drafts and versions | Drafts and version history | |
| Scheduled publish | Scheduled publishing | |
| Live preview | Live preview with click-to-select | See [Set up the live preview](https://docs.bifrostorbit.com/cms/developers/preview/) |
| SEO plugin (`meta`) | The entry's SEO | |
| Redirects plugin | Redirects | Import the plugin's `redirects` collection as rows |
| Hooks, access control and custom endpoints | Webhooks, roles and the Management API | |

Field types:

| Payload | CMS Orbit |
| --- | --- |
| `text` | `text` |
| `textarea` | `textarea` |
| `richText` (Lexical) | `richtext`, or a list of blocks |
| `email` | `text` |
| `number` | `number` |
| `checkbox` | `boolean` |
| `date` | `date`, `datetime` or `time`, by its picker |
| `select` with `hasMany` off or on | `select`, `multiselect` |
| `radio` | `select` |
| `upload` | `asset`, or `assets` with `hasMany` |
| `relationship` | `reference`, `references` or `link` |
| `blocks` | The page's blocks, or a `components` slot |
| `array` | `components` slot |
| `group` | Fields on the parent, or a `component` slot |
| `tabs`, `row`, `collapsible` | Only layout in the admin: their fields go on the parent. Use `group` on a CMS Orbit field to group them in the editor. |
| `point` | Not yet: use two `number` fields |
| `json`, `code` | Not yet: model the data as fields, or keep it in a `textarea` |
| `join` | Not needed: read the other side with a filter on the website |

## Before you start

- An **API key** for a Payload user with read access to every collection. Turn on `auth: { useAPIKey: true }` on your users collection, then create the key on the user's page in the admin. Or run the script inside your project with the Local API; see [Read with the Local API](#read-with-the-local-api).
- 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

Open your collection configs, often in `src/collections/`, and your blocks, often in `src/blocks/`. For each collection with pages, write a CMS Orbit content type; for each block, a component. Write them in a `schema.mjs` and create them with [Schema as code](https://docs.bifrostorbit.com/cms/developers/schema-as-code/). The move is mostly mechanical: Payload's `name` becomes the field `key`, its `label` the field `name`, and `required` stays `required`.

The script below assumes the journal model from that guide, plus these Payload collections and blocks:

| Payload | CMS Orbit |
| --- | --- |
| `posts` with `title`, `slug`, `excerpt`, `publishedAt`, `heroImage`, `author`, `categories`, `meta` and a `layout` blocks field | `journalPost` |
| `authors` with `name`, `slug`, `bio` (Lexical) and `photo` | `author` |
| `categories` with `title` and `slug` | Terms of the `topics` taxonomy |
| `richText` block with `content` (Lexical) | `text` blocks, with an `imageBlock` for each image |
| `mediaBlock` with `media` and `caption` | `imageBlock` |
| `gearGrid` block with `title` and an `items` array of `name` and `link` | `gearList` with `gearItem` blocks in its `items` slot |

## 2. Bring categories across

A collection that only exists to tag other documents, such as `categories`, becomes a taxonomy, and each document a term: its slug is the term's value and its title 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**.

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 Payload's Lexical package for its HTML converter, with `payload`, which it needs. Use the version your project runs:

```bash
npm install @payloadcms/richtext-lexical payload
```

The script reads each collection with the [REST API](https://payloadcms.com/docs/rest-api/overview), `GET /api/<collection slug>`, 100 documents a page with `limit` and `page`, until `hasNextPage` is false. `depth=1` fills in uploads and relationships one level deep, so images arrive with their address. `draft=true` reads the newest draft where a collection has drafts turned on. It reads each locale with `locale=` and `fallback-locale=none`, so untranslated fields arrive empty instead of in the main language, and writes `import.json` and `topics.csv`:

```ts
// payload.ts
import { writeFile } from 'node:fs/promises'
import { convertLexicalToHTML, LinkHTMLConverter } from '@payloadcms/richtext-lexical/html'
import type { HTMLConvertersFunction } from '@payloadcms/richtext-lexical/html'
import type { SerializedEditorState, SerializedLexicalNode } from '@payloadcms/richtext-lexical/lexical'

const PAYLOAD = process.env.PAYLOAD_URL ?? 'https://admin.northwilds.com'
const API_KEY = process.env.PAYLOAD_API_KEY
const SITE = 'https://northwilds.com'
const MAIN = 'en'
const LANGUAGES: Record<string, string> = { en: 'en-GB', nb: 'nb-NO', de: 'de-DE' }

type Media = { id: string; url: string; filename: string; alt?: string | null }
type Link = { type: 'reference' | 'custom'; url?: string | null; reference?: { relationTo: string; value: { id: string } | string } | null }
type LayoutBlock =
  | { blockType: 'richText'; content: SerializedEditorState }
  | { blockType: 'mediaBlock'; media: Media | null; caption?: string | null }
  | { blockType: 'gearGrid'; title: string; items: { name: string; link: Link | null }[] }
type Post = {
  id: string
  title: string | null
  slug: string
  excerpt: string | null
  publishedAt: string | null
  heroImage: Media | null
  author: { id: string } | null
  categories: { slug: string }[]
  meta?: { title?: string | null; description?: string | null }
  layout: LayoutBlock[] | null
}
type Author = { id: string; name: string; slug: string; bio: SerializedEditorState | null; photo: Media | null }
type Category = { id: string; title: string | null; slug: string }

type Block = { type: string; fields: Record<string, unknown>; children?: Record<string, Block[]> }

async function all<T>(collection: string, locale: string): Promise<T[]> {
  const docs: T[] = []
  for (let page = 1; ; page += 1) {
    const params = new URLSearchParams({
      limit: '100',
      page: String(page),
      depth: '1',
      draft: 'true',
      locale,
      'fallback-locale': 'none',
    })
    const response = await fetch(`${PAYLOAD}/api/${collection}?${params}`, {
      headers: { Authorization: `users API-Key ${API_KEY}` },
    })
    if (!response.ok) throw new Error(`Payload answered ${response.status} for ${collection}`)
    const result = (await response.json()) as { docs: T[]; hasNextPage: boolean }
    docs.push(...result.docs)
    if (!result.hasNextPage) return docs
  }
}

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

const posts = await read<Post>('posts')
const authors = await read<Author>('authors')
const categories = await read<Category>('categories')

const slugs = new Map(posts[MAIN].map((post) => [post.id, post.slug]))
const newUrl = (slug: string) => `/journal/${slug}`
const idOf = (value: { id: string } | string) => (typeof value === 'string' ? value : value.id)

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

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

function link(value: Link | null) {
  if (value?.type === 'reference' && value.reference) return { $link: idOf(value.reference.value) }
  if (value?.url) return { kind: 'url', href: localPath(value.url) }
  return null
}

const converters: HTMLConvertersFunction = ({ defaultConverters }) => ({
  ...defaultConverters,
  ...LinkHTMLConverter({
    internalDocToHref: ({ linkNode }) => {
      const doc = linkNode.fields.doc
      if (doc?.relationTo !== 'posts') return '#'
      const value = doc.value as { id: string; slug?: string } | string
      const slug = typeof value === 'string' ? slugs.get(value) : (value.slug ?? slugs.get(value.id))
      return slug ? newUrl(slug) : '#'
    },
  }),
})

function richText(state: SerializedEditorState | null | undefined): Block[] {
  if (!state) return []
  const blocks: Block[] = []
  let text: SerializedLexicalNode[] = []
  const flush = () => {
    const data = { root: { ...state.root, children: text } } as SerializedEditorState
    const html = convertLexicalToHTML({ data, converters, disableContainer: true })
    if (html.trim()) blocks.push({ type: 'text', fields: { text: html.replace(/href="([^"]+)"/g, (_, href) => `href="${localPath(href)}"`) } })
    text = []
  }
  for (const node of state.root.children) {
    if (node.type === 'upload') {
      flush()
      const image = asset((node as SerializedLexicalNode & { value: Media }).value)
      if (image) blocks.push({ type: 'imageBlock', fields: { image } })
    } else if (node.type === 'block') {
      flush()
      const fields = (node as SerializedLexicalNode & { fields: LayoutBlock }).fields
      blocks.push(...layout([fields]))
    } else {
      text.push(node)
    }
  }
  flush()
  return blocks
}

function layout(list: LayoutBlock[] | null): Block[] {
  return (list ?? []).flatMap((block): Block[] => {
    switch (block.blockType) {
      case 'richText':
        return richText(block.content)
      case 'mediaBlock':
        return [{ type: 'imageBlock', fields: { image: asset(block.media), caption: block.caption ?? null } }]
      case 'gearGrid':
        return [{
          type: 'gearList',
          fields: { heading: block.title },
          children: { items: block.items.map((item) => ({ type: 'gearItem', fields: { name: item.name, link: link(item.link) } })) },
        }]
      default:
        console.warn(`No mapping for the ${(block as { blockType: string }).blockType} block`)
        return []
    }
  })
}

const filled = (fields: Record<string, unknown>) =>
  Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== null && value !== undefined && value !== ''))

function post(item: Post) {
  return {
    name: item.title ?? '',
    slug: item.slug,
    url: newUrl(item.slug),
    fields: {
      excerpt: item.excerpt,
      publishedOn: item.publishedAt?.slice(0, 10) ?? null,
      cover: asset(item.heroImage),
      author: item.author ? { $ref: item.author.id } : null,
      topics: item.categories.map((category) => category.slug),
    },
    components: layout(item.layout),
    ...(item.meta?.title || item.meta?.description
      ? { seo: { title: item.meta.title ?? null, description: item.meta.description ?? null } }
      : {}),
  }
}

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

const others = Object.keys(LANGUAGES).filter((code) => code !== MAIN)

function translations<T extends { id: string }, R extends { name: string; fields: Record<string, unknown>; components?: Block[] }>(
  lists: Record<string, T[]>,
  item: T,
  map: (item: T) => R,
) {
  const out: Record<string, unknown> = {}
  for (const code of others) {
    const other = lists[code].find((candidate) => candidate.id === item.id)
    if (!other) continue
    const translated = map(other)
    out[LANGUAGES[code]] = {
      ...translated,
      name: translated.name || undefined,
      fields: filled(translated.fields),
      components: translated.components?.length ? translated.components : undefined,
    }
  }
  return out
}

const entries = [
  ...authors[MAIN].map((item) => ({ key: item.id, type: 'author', ...author(item), translations: translations(authors, item, author) })),
  ...posts[MAIN].map((item) => ({ key: item.id, type: 'journalPost', ...post(item), translations: translations(posts, item, post) })),
]

const cell = (value: string) => (/[",;\n]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value)
const header = ['value', 'label', ...others.map((code) => `label:${LANGUAGES[code]}`)]
const rows = categories[MAIN].map((category) => [
  category.slug,
  category.title ?? category.slug,
  ...others.map((code) => categories[code].find((other) => other.id === category.id)?.title ?? ''),
])
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: posts[MAIN].map((item) => ({ from: `/posts/${item.slug}`, to: newUrl(item.slug) })),
}, null, 2))
console.log(`Wrote ${entries.length} entries to import.json and ${rows.length} categories to topics.csv`)
```

```bash
export PAYLOAD_URL=https://admin.northwilds.com PAYLOAD_API_KEY=<API key>
node payload.ts
```

What it does with the parts that need thought:

- **Blocks fields:** each block in `layout` arrives with its `blockType`, and `layout` turns it into a CMS Orbit block. A block without a mapping is left out with a warning. The `gearGrid` block's `items` array becomes `gearItem` blocks in the `gearList` block's `items` slot, under `children`.
- **Lexical rich text** becomes HTML with `convertLexicalToHTML` from `@payloadcms/richtext-lexical/html`, for each run of paragraphs, headings, lists, quotes and tables. An upload node becomes an `imageBlock`, since rich text in CMS Orbit holds no images, and a block inside the rich text goes through `layout` like the blocks field. `disableContainer` leaves out the wrapping `<div>`.
- **Internal links** in rich text use `internalDocToHref`, which gives a link to a post its new address, from the linked post's `slug`. Add the other collections your editors link to; a link it cannot place becomes `#`, so search the import file for `href="#"` before importing.
- **Relationships:** `author` becomes a `$ref` to the author's entry, by its Payload `id`. A link field that points at a document becomes a `$link`, so it follows the page when it moves. A polymorphic relationship arrives as `{ relationTo, value }`; use `relationTo` to choose the entry it points at. `categories` becomes the categories' slugs, the values of the terms in `topics.csv`.
- **Uploads:** with local storage, Payload answers addresses such as `/api/media/file/ridge.jpg`, so the script puts the Payload address in front. Files in S3 or another storage adapter may already have a full address. If your upload collection limits who may read files, let the import read them during the migration, since it downloads them without the API key. Each file's `alt` becomes its alt text in the main language; add the others before publishing.
- **Localization:** a Payload document has one `id` and a value per locale in each localised field. The script reads every locale with `fallback-locale=none`, keeps only the fields that have a value, and attaches them to the entry as its translation, with its own name, slug and address. Fields that are not localised arrive the same in every locale, which does no harm.
- **Drafts and versions:** `draft=true` reads the newest draft of collections with drafts turned on, including changes not yet published; leave it out to bring only what is published. Versions are not brought across.
- **SEO:** the official SEO plugin keeps the title and description in `meta`, which the script sends as the entry's SEO.
- **Addresses:** `newUrl` builds the new addresses from the slug, and `redirects` lists the old website addresses, here `/posts/{slug}`, that should move to `/journal/{slug}`. If you used the official Redirects plugin, read its `redirects` collection the same way and add each row, with `from` and `to.url`, to `redirects`.

Globals are at `GET /api/globals/<global slug>`, without pagination. A header or footer global usually becomes a menu; recreate it under **Menus** or with the Management API.

### Read with the Local API

To read the database directly, without the REST API or an API key, run the reading part inside your Payload project with `payload run`. `getPayload({ config })` gives the Local API, and `payload.find({ collection: 'posts', limit: 100, page, depth: 1, draft: true, locale, fallbackLocale: false })` answers the same `docs` and `hasNextPage` as the REST API, so the rest of the script stays the same.

## 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 block 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 Local API, REST or GraphQL calls with the SDK. See [Connect a website](https://docs.bifrostorbit.com/cms/developers/connect-a-website/):

   ```ts
   // Before: Payload
   const { docs } = await payload.find({ collection: 'posts', where: { slug: { equals: slug } }, locale: 'nb' })

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

3. Rich text arrives as HTML: replace `RichText` from `@payloadcms/richtext-lexical/react` with the SDK's `<RichText value={block.text} />`. See [SDK](https://docs.bifrostorbit.com/cms/developers/sdk/).
4. Replace Payload's live preview with CMS Orbit's, and mark blocks with `data-cms-id`. See [Set up the live preview](https://docs.bifrostorbit.com/cms/developers/preview/).
5. Replace `afterChange` hooks that revalidate your website with CMS Orbit's webhooks. See [Webhooks](https://docs.bifrostorbit.com/cms/developers/webhooks/).
6. Promote the content to Production, deploy, and check that old addresses redirect. Once nothing reads Payload any more, it can be removed from your Next.js app.

## What does not come across

- **Versions and autosaves.** Each entry starts with one draft.
- **Hooks, access control functions and custom endpoints.** Use roles, webhooks and the Management API in CMS Orbit.
- **Custom admin components and custom fields.** Use CMS Orbit's field types.
- **`json`, `code` and `point` fields.** Model the data as fields.
- **Auth collections and their users.** People sign in with Orbit and get roles in CMS Orbit. Website accounts held in Payload need a home of their own.
