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.
How-to guide15 min read
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. 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.
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
id across all localeslayoutcomponent slot holding one blockmediarelationTo several collections)meta)redirects collection as rowsField types:
texttexttextareatextarearichText (Lexical)richtext, or a list of blocksemailtextnumbernumbercheckboxbooleandatedate, datetime or time, by its pickerselect with hasMany off or onselect, multiselectradioselectuploadasset, or assets with hasManyrelationshipreference, references or linkblockscomponents slotarraycomponents slotgroupcomponent slottabs, row, collapsiblegroup on a CMS Orbit field to group them in the editor.pointnumber fieldsjson, codetextareajoinBefore 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. - 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.
- Node 24, which runs the TypeScript scripts below as they are. Work in a folder whose
package.jsonhas"type": "module", such as one made withnpm init -y && npm pkg set type=module.
1Recreate 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. 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:
posts with title, slug, excerpt, publishedAt, heroImage, author, categories, meta and a layout blocks fieldjournalPostauthors with name, slug, bio (Lexical) and photoauthorcategories with title and slugtopics taxonomyrichText block with content (Lexical)text blocks, with an imageBlock for each imagemediaBlock with media and captionimageBlockgearGrid block with title and an items array of name and linkgearList with gearItem blocks in its items slot2Bring 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:
value,label,label:nb-NO,label:de-DEski-touring,Ski touring,Topptur,Skitourensea-kayaking,Sea kayaking,Havpadling,Seekajak- In CMS Orbit, open Schema › Taxonomies and create the taxonomy, with the key
topics. - Choose Import CSV and pick
topics.csv. The preview shows each term as new; choose Import.
See Tag content with taxonomies. The Management API imports the same file with POST/taxonomies/topics/import.
3Read and transform the documents
Install Payload's Lexical package for its HTML converter, with payload, which it needs. Use the version your project runs:
npm install @payloadcms/richtext-lexical payloadThe script reads each collection with the REST API, 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:
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_KEYconst 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`)export PAYLOAD_URL=https://admin.northwilds.com PAYLOAD_API_KEY=<API key>node payload.tsWhat it does with the parts that need thought:
- Blocks fields: each block in
layoutarrives with itsblockType, andlayoutturns it into a CMS Orbit block. A block without a mapping is left out with a warning. ThegearGridblock'sitemsarray becomesgearItemblocks in thegearListblock'sitemsslot, underchildren. - Lexical rich text becomes HTML with
convertLexicalToHTMLfrom@payloadcms/richtext-lexical/html, for each run of paragraphs, headings, lists, quotes and tables. An upload node becomes animageBlock, since rich text in CMS Orbit holds no images, and a block inside the rich text goes throughlayoutlike the blocks field.disableContainerleaves 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'sslug. Add the other collections your editors link to; a link it cannot place becomes#, so search the import file forhref="#"before importing. - Relationships:
authorbecomes a$refto the author's entry, by its Payloadid. 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 }; userelationToto choose the entry it points at.categoriesbecomes the categories' slugs, the values of the terms intopics.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'saltbecomes its alt text in the main language; add the others before publishing. - Localization: a Payload document has one
idand a value per locale in each localised field. The script reads every locale withfallback-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=truereads 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:
newUrlbuilds the new addresses from the slug, andredirectslists the old website addresses, here/posts/{slug}, that should move to/journal/{slug}. If you used the official Redirects plugin, read itsredirectscollection the same way and add each row, withfromandto.url, toredirects.
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.
4Import
Check the file with a dry run, then run the import, with cms-orbit from Import content with the Management API:
npx cms-orbit import import.json --dry-runnpx cms-orbit import import.jsonCheck 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.
5Switch the website
- Register your block components under the new component keys. With the SDK, a component gets
blockwith its fields, and nested blocks asblock.itemsor throughCmsBlocks. See Render components. - Replace Local API, REST or GraphQL calls with the SDK. See 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' }) ```
- Rich text arrives as HTML: replace
RichTextfrom@payloadcms/richtext-lexical/reactwith the SDK's<RichText value={block.text} />. See SDK. - Replace Payload's live preview with CMS Orbit's, and mark blocks with
data-cms-id. See Set up the live preview. - Replace
afterChangehooks that revalidate your website with CMS Orbit's webhooks. See Webhooks. - 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,codeandpointfields. 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.
Was this page helpful?